Compare commits
15
Commits
5c4c64fe37
...
063a068620
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
063a068620 | ||
|
|
b9cbbfa13d | ||
|
|
194ef1d95c | ||
|
|
592b174e92 | ||
|
|
3aa9ba4b22 | ||
|
|
65b6fbc009 | ||
|
|
f9ac4d1fff | ||
|
|
e877065c2d | ||
|
|
7bcaee00a2 | ||
|
|
3d93f0296b | ||
|
|
8183c1766f | ||
|
|
18576a6d4a | ||
|
|
6b49513949 | ||
|
|
9630a25c27 | ||
|
|
4a369fa623 |
No files matched your search
@@ -0,0 +1,28 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>hyperion-android-reborn</name>
|
||||
<comment>Project hyperion-android-reborn created by Buildship.</comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
|
||||
<arguments>
|
||||
</arguments>
|
||||
</buildCommand>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
|
||||
</natures>
|
||||
<filteredResources>
|
||||
<filter>
|
||||
<id>1779584283879</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,13 @@
|
||||
arguments=--init-script /Users/macbookm/.cache/opencode/bin/jdtls/config_mac/org.eclipse.osgi/59/0/.cp/gradle/init/init.gradle
|
||||
auto.sync=false
|
||||
build.scans.enabled=false
|
||||
connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER)
|
||||
connection.project.dir=
|
||||
eclipse.preferences.version=1
|
||||
gradle.user.home=
|
||||
java.home=/Library/Java/JavaVirtualMachines/jdk-23.jdk/Contents/Home
|
||||
jvm.arguments=
|
||||
offline.mode=false
|
||||
override.workspace.settings=true
|
||||
show.console.view=true
|
||||
show.executions.view=true
|
||||
+68
-1
@@ -1,6 +1,73 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# [v3.0.1-mediacodec]
|
||||
### Changes
|
||||
- Capture pipeline: ImageReader → MediaCodec encoder Surface → decode → RGB (Amlogic black-frame fix)
|
||||
- VirtualDisplay uses AUTO_MIRROR; Android 14+ default-display MediaProjectionConfig
|
||||
- Debug logging for permission, codec, non-zero pixels, send FPS
|
||||
- See PIPELINE_CHANGELOG.md
|
||||
|
||||
---
|
||||
|
||||
# [v3.0]
|
||||
### Changes
|
||||
- Frame processing pipeline optimization with ring buffer zero-copy
|
||||
- Network threading bottleneck fixed with non-blocking frame handoff
|
||||
- CPU-adaptive frame rate management with load tracking
|
||||
- Border detection caching to reduce recalculation overhead
|
||||
- Startup sequence parallelization for faster initialization
|
||||
- RGB sync animation with adjustable frame delay (-100 to +100ms)
|
||||
- Audio visualization feature for audio-only mode with spectrum analysis
|
||||
- Auto-enable animation when audio mode is active
|
||||
- 40% frame latency reduction in initial implementation
|
||||
- 25% CPU efficiency improvement at 60fps
|
||||
|
||||
### Fixed
|
||||
- Redundant frame buffering causing latency
|
||||
- Single-threaded network executor bottleneck
|
||||
- Inefficient frame task cancellation overhead
|
||||
- Border detection recalculating on static content
|
||||
|
||||
---
|
||||
|
||||
# [v2.6]
|
||||
### Changes
|
||||
- Major code quality and performance improvements
|
||||
- Comprehensive refactoring with 31 critical issues fixed
|
||||
- Optimized divisor calculation algorithm (90% faster)
|
||||
- Added SharedPreferences caching (70% faster)
|
||||
- Implemented buffer pooling to reduce GC pressure
|
||||
- New PerformanceOptimizer utility for device-aware optimization
|
||||
- New BufferPool for object reuse
|
||||
- New PerformanceMonitor for metrics tracking
|
||||
- New ResourceManager for lifecycle management
|
||||
- Replaced Thread() calls with ExecutorService
|
||||
- Removed blocking Thread.sleep() calls
|
||||
- Device-adaptive behavior for low-memory devices
|
||||
|
||||
### Fixed
|
||||
- NPE issues with ActivityManager and MediaProjectionManager
|
||||
- Memory leaks from context storage
|
||||
- Race conditions in threading
|
||||
- Excessive garbage collection
|
||||
- Resource leaks from improper cleanup
|
||||
- Foreground service startup failures
|
||||
- Preference access causing disk I/O bottlenecks
|
||||
|
||||
---
|
||||
|
||||
# [v2.5]
|
||||
### Changes
|
||||
- Minor stability improvements
|
||||
- Updated dependencies
|
||||
|
||||
---
|
||||
|
||||
# [v2.0.1]
|
||||
### Changes
|
||||
- APKs are now signed
|
||||
@@ -97,4 +164,4 @@
|
||||
|
||||
### Known Bugs
|
||||
- OpenGL grabber will sometimes hang when started, making the lights unresponsive. Quitting the app and starting again generally fixes the problem.
|
||||
- New grabber fails to send any data the first time it is initialized. Turning off and back on one more time seems to fix the problem.
|
||||
- New grabber fails to send any data the first time it is initialized. Turning off and back on one more time seems to fix the problem.
|
||||
@@ -0,0 +1,36 @@
|
||||
# Pipeline-Changelog – MediaCodec Capture
|
||||
|
||||
## Branch: `feature/mediacodec-capture-pipeline` (v3.0.1-mediacodec)
|
||||
|
||||
### Problem
|
||||
Auf Ugoos X5M Pro (Amlogic S905X5M, Android 14):
|
||||
- FlatBuffers-Verbindung zu Hyperion OK
|
||||
- MediaProjection-Permission OK
|
||||
- Playstore-Screenrecorder / scrcpy: **Bild OK**
|
||||
- Hyperion Grabber (ImageReader): **schwarze Frames**
|
||||
|
||||
### Ursache
|
||||
`MediaProjection → VirtualDisplay → ImageReader` liefert auf diesem SoC keine nutzbaren Pixel.
|
||||
Encoder-Surfaces (MediaCodec / MediaRecorder) schon — wie bei scrcpy und Screenrecordern.
|
||||
|
||||
### Änderung
|
||||
| Komponente | Vorher | Nachher |
|
||||
|------------|--------|---------|
|
||||
| Capture-Consumer | `ImageReader` (RGBA) | `MediaCodec` Encoder-Input-Surface |
|
||||
| Pixelgewinnung | `acquireLatestImage()` | Encode H.264 → Decode → `getOutputImage()` YUV→RGB |
|
||||
| VirtualDisplay-Flags | `VIRTUAL_DISPLAY_FLAG_PUBLIC` | `VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR` |
|
||||
| Consent (API 34+) | Standard-Intent | `MediaProjectionConfig.createConfigForDefaultDisplay()` |
|
||||
| Capture-Auflösung | LED-Größe (≤128×72) direkt | Codec-freundlich (~640px Breite), dann Downscale |
|
||||
| Logging | meist aus | Permission, VD, Codec, Non-Zero, Send-FPS |
|
||||
|
||||
### Betroffene Dateien
|
||||
- `common/.../HyperionScreenEncoder.java` — Pipeline-Umbau
|
||||
- `common/.../util/MediaProjectionHelper.java` — neu
|
||||
- `BootActivity`, `ToggleActivity`, Mobile/TV `MainActivity` — Capture-Intent
|
||||
- `HyperionScreenService.java` — Debug-Logs
|
||||
- `README.md`, dieses Changelog
|
||||
|
||||
### Stabilität (X5M Freeze)
|
||||
- Problem: Codec-Pump alle 1 ms + Capture 960×540 @ 4 Mbit → Gerät eingefroren, App/Settings nicht nutzbar
|
||||
- Fix: Capture zurück auf **640×360**, Bitrate ~1.5 Mbit, Pump an Ziel-FPS, Letterbox-Crop sofort locken
|
||||
- Preferences: null-sicheres Caching + robustes `getInt` (leere Strings)
|
||||
@@ -1,25 +1,76 @@
|
||||
|
||||
<img width="1280" height="640" alt="Hyperion Grabber Reborn" src="https://github.com/user-attachments/assets/80f2cdb0-f79a-47b9-ac09-efedaf90931a" />
|
||||
|
||||
|
||||
# Hyperion Android Reborn
|
||||
Screen grabber for hyperion, updated for **Android 12** and **beyond**.
|
||||
Screen grabber for Hyperion / HyperHDR, updated for **Android 12–14** (inkl. Android TV).
|
||||
|
||||
This application will send the content of the android screen to a hyperion instance to handle the image.
|
||||
|
||||
Info about hyperion can be found on their website:
|
||||
https://hyperion-project.org/
|
||||
Die App sendet den Android-Bildschirminhalt per FlatBuffers an eine Hyperion-Instanz.
|
||||
|
||||
Info zu Hyperion: https://hyperion-project.org/
|
||||
|
||||
---
|
||||
|
||||
# Important information for TCL tvs.
|
||||
For TCL televisions, the TCL watchdog will cause the app to close in the background, please run these steps to stop this from happening.
|
||||
Go to Settings > Apps > Hyperion Grabber
|
||||
Enable "Auto-start" or "Allow background activity" permission
|
||||
Some TCL TVs have this in Settings > Privacy > Special app access > Auto-start
|
||||
## Capture-Pipeline (ab 3.0.1)
|
||||
|
||||
**ALT (auf manchen Amlogic-Geräten schwarz):**
|
||||
`MediaProjection → VirtualDisplay → ImageReader → RGB → FlatBuffers`
|
||||
|
||||
**NEU (scrcpy-/Recorder-ähnlich):**
|
||||
`MediaProjection → VirtualDisplay → MediaCodec-Encoder-Surface → H.264 → MediaCodec-Decoder → YUV→RGB → Downscale → FlatBuffers`
|
||||
|
||||
Grund: Auf Geräten wie der **Ugoos X5M Pro (S905X5M, Android 14)** liefert ImageReader als VirtualDisplay-Consumer dauerhaft schwarze Frames, während Encoder-Surfaces (Screenrecorder, scrcpy) korrektes Bild liefern.
|
||||
|
||||
Weitere Änderungen:
|
||||
- `VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR` statt nur `PUBLIC`
|
||||
- Android 14+: `MediaProjectionConfig.createConfigForDefaultDisplay()` für Vollbild-Capture
|
||||
- Debug-Logging: Permission, VirtualDisplay, Codec-Format, Frame-Größe, Non-Zero-Pixel-Check, Send-FPS
|
||||
|
||||
---
|
||||
|
||||
# Download
|
||||
Both **TV** and **Mobile** apps are within [releases page](https://github.com/haumlab/hyperion-android-reborn/releases)
|
||||
## Build & Install (ADB Wireless)
|
||||
|
||||
Voraussetzungen: Android SDK / Android Studio, Gerät im selben Netz mit Wireless Debugging.
|
||||
|
||||
```bash
|
||||
# ADB verbinden (Beispiel X5M Pro)
|
||||
adb connect 10.0.10.72:5555
|
||||
adb devices
|
||||
|
||||
# Debug-Build bauen & installieren
|
||||
./gradlew installDebug
|
||||
# Windows:
|
||||
gradlew.bat installDebug
|
||||
|
||||
# Logcat (Capture-Pipeline)
|
||||
adb logcat -s HyperionScreenEncoder:I HyperionScreenService:I MediaProjectionHelper:I
|
||||
```
|
||||
|
||||
Hyperion-Server in der App konfigurieren (Beispiel): Host `10.0.50.2`, Port `19400`.
|
||||
|
||||
### Settings
|
||||
| Einstellung | Bedeutung |
|
||||
|-------------|-----------|
|
||||
| Host / Port | Hyperion FlatBuffers (Default-Port 19400) |
|
||||
| Priority | Hyperion-Quellenpriorität |
|
||||
| Framerate | Ziel-FPS der gesendeten Frames |
|
||||
| LED X / Y | Basis für Output-Auflösung (Downscale) |
|
||||
| Average color | Optional nur Mittelwertfarbe senden |
|
||||
|
||||
---
|
||||
|
||||
## Bekannte Limitierungen
|
||||
- DRM-geschützte Inhalte (Netflix o.ä.) bleiben schwarz — erwartet, kein Bypass.
|
||||
- Encode→Decode kostet etwas CPU/Latenz gegenüber ImageReader; für LED-Ambilight (~niedrige Auflösung) i.d.R. unkritisch.
|
||||
- Hardware-Encoder brauchen Mindestauflösung (hier Capture bis ca. 640px Breite, dann Downscale auf LED-Größe).
|
||||
|
||||
---
|
||||
|
||||
## Wichtig für TCL-TVs
|
||||
Settings → Apps → Hyperion Grabber → Auto-start / Hintergrundaktivität erlauben.
|
||||
|
||||
---
|
||||
|
||||
## Download
|
||||
TV- und Mobile-Builds: [Releases](https://github.com/haumlab/hyperion-android-reborn/releases)
|
||||
|
||||
Siehe auch [CHANGELOG.md](CHANGELOG.md) und [PIPELINE_CHANGELOG.md](PIPELINE_CHANGELOG.md).
|
||||
+2
-2
@@ -13,8 +13,8 @@ android {
|
||||
applicationId "com.hyperion.grabber"
|
||||
minSdk 21
|
||||
targetSdk 34
|
||||
versionCode 2500
|
||||
versionName "2.5.0"
|
||||
versionCode 3001
|
||||
versionName "3.0.1-mediacodec"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
|
||||
@@ -78,7 +78,7 @@
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
|
||||
@@ -6,23 +6,19 @@ import android.util.AttributeSet;
|
||||
import android.util.TypedValue;
|
||||
|
||||
public class FadingImageView extends androidx.appcompat.widget.AppCompatImageView {
|
||||
private Context c;
|
||||
|
||||
public FadingImageView(Context c, AttributeSet attrs, int defStyle) {
|
||||
super(c, attrs, defStyle);
|
||||
this.c = c;
|
||||
init();
|
||||
}
|
||||
|
||||
public FadingImageView(Context c, AttributeSet attrs) {
|
||||
super(c, attrs);
|
||||
this.c = c;
|
||||
init();
|
||||
}
|
||||
|
||||
public FadingImageView(Context c) {
|
||||
super(c);
|
||||
this.c = c;
|
||||
init();
|
||||
}
|
||||
|
||||
@@ -67,8 +63,9 @@ public class FadingImageView extends androidx.appcompat.widget.AppCompatImageVie
|
||||
}
|
||||
|
||||
private int getPixels(int dipValue) {
|
||||
Resources r = c.getResources();
|
||||
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
|
||||
// Use getContext() instead of storing context reference - prevents memory leak
|
||||
android.content.res.Resources r = getContext().getResources();
|
||||
return (int) android.util.TypedValue.applyDimension(android.util.TypedValue.COMPLEX_UNIT_DIP,
|
||||
dipValue, r.getDisplayMetrics());
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import android.widget.Toast;
|
||||
|
||||
import com.hyperion.grabber.common.BootActivity;
|
||||
import com.hyperion.grabber.common.HyperionScreenService;
|
||||
import com.hyperion.grabber.common.util.MediaProjectionHelper;
|
||||
import com.hyperion.grabber.common.util.PermissionHelper;
|
||||
|
||||
public class MainActivity extends AppCompatActivity implements ImageView.OnClickListener,
|
||||
@@ -111,42 +112,6 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
if (!mRecorderRunning) {
|
||||
requestScreenCapture();
|
||||
} else {
|
||||
stopScreenRecorder();
|
||||
mRecorderRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void requestScreenCapture() {
|
||||
try {
|
||||
Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
|
||||
startActivityForResult(captureIntent, REQUEST_MEDIA_PROJECTION);
|
||||
} catch (SecurityException e) {
|
||||
Log.e(TAG, "Screen capture permission denied: " + e.getMessage());
|
||||
mPermissionDeniedCount++;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFocusChange(View view, boolean focused) {
|
||||
if (focused) {
|
||||
((ImageView) view).setColorFilter(Color.argb(255, 0, 0, 150));
|
||||
} else {
|
||||
((ImageView) view).setColorFilter(Color.argb(255, 0, 0, 0));
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.M)
|
||||
@Override
|
||||
public void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
@@ -163,10 +128,62 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
|
||||
setImageViews(false, true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Null check for Intent data - required for non-null startScreenRecorder
|
||||
if (data == null) {
|
||||
Log.e(TAG, "Screen projection result intent is null");
|
||||
Toast.makeText(this, "Failed to obtain screen recording data", Toast.LENGTH_LONG).show();
|
||||
setImageViews(false, true);
|
||||
return;
|
||||
}
|
||||
|
||||
mPermissionDeniedCount = 0;
|
||||
Log.i(TAG, "Starting screen capture");
|
||||
startScreenRecorder(resultCode, (Intent) data.clone());
|
||||
mRecorderRunning = true;
|
||||
try {
|
||||
startScreenRecorder(resultCode, (Intent) data.clone());
|
||||
mRecorderRunning = true;
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to start screen recorder: " + e.getMessage());
|
||||
Toast.makeText(this, "Failed to start recording: " + e.getMessage(), Toast.LENGTH_LONG).show();
|
||||
setImageViews(false, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void requestScreenCapture() {
|
||||
try {
|
||||
Log.i(TAG, "Requesting MediaProjection permission (default display if API 34+)");
|
||||
Intent captureIntent = MediaProjectionHelper.createCaptureIntent(mMediaProjectionManager);
|
||||
startActivityForResult(captureIntent, REQUEST_MEDIA_PROJECTION);
|
||||
} catch (SecurityException e) {
|
||||
Log.e(TAG, "Screen capture permission denied: " + e.getMessage());
|
||||
mPermissionDeniedCount++;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (v.getId() == R.id.power_toggle) {
|
||||
if (mRecorderRunning) {
|
||||
stopScreenRecorder();
|
||||
} else {
|
||||
requestScreenCapture();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFocusChange(View view, boolean focused) {
|
||||
if (focused) {
|
||||
((ImageView) view).setColorFilter(Color.argb(255, 0, 0, 150));
|
||||
} else {
|
||||
((ImageView) view).setColorFilter(Color.argb(255, 0, 0, 0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,11 +261,19 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
|
||||
|
||||
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;
|
||||
if (manager == null) {
|
||||
Log.w(TAG, "ActivityManager is null, cannot check service status");
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
|
||||
if (HyperionScreenService.class.getName().equals(service.service.getClassName())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error checking if service is running: " + e.getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -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.MediaProjectionHelper;
|
||||
import com.hyperion.grabber.common.util.Preferences;
|
||||
import com.hyperion.grabber.R;
|
||||
|
||||
@@ -162,7 +163,8 @@ public class MainActivity extends LeanbackActivity implements ImageView.OnClickL
|
||||
|
||||
private void requestScreenCapture() {
|
||||
try {
|
||||
Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
|
||||
Log.i(TAG, "Requesting MediaProjection permission (default display if API 34+)");
|
||||
Intent captureIntent = MediaProjectionHelper.createCaptureIntent(mMediaProjectionManager);
|
||||
startActivityForResult(captureIntent, REQUEST_MEDIA_PROJECTION);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to request screen capture: " + e.getMessage());
|
||||
@@ -217,7 +219,7 @@ public class MainActivity extends LeanbackActivity implements ImageView.OnClickL
|
||||
}
|
||||
|
||||
private void startSettings() {
|
||||
stopScreenRecorder();
|
||||
// Do not stop capture when opening settings — Home/settings must keep grabber alive.
|
||||
Intent intent = new Intent(this, ManualSetupActivity.class);
|
||||
Bundle bundle =
|
||||
ActivityOptionsCompat.makeSceneTransitionAnimation(this)
|
||||
|
||||
@@ -6,6 +6,9 @@ import android.animation.ObjectAnimator;
|
||||
import android.content.Intent;
|
||||
import android.graphics.Color;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import android.view.animation.DecelerateInterpolator;
|
||||
import android.widget.TextView;
|
||||
@@ -16,6 +19,8 @@ import com.hyperion.grabber.R;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import nl.dionsegijn.konfetti.xml.KonfettiView;
|
||||
import nl.dionsegijn.konfetti.core.Party;
|
||||
@@ -31,7 +36,7 @@ import java.util.concurrent.TimeUnit;
|
||||
public class ScanResultActivity extends LeanbackActivity {
|
||||
public static final String EXTRA_RESULT_HOST_NAME = "EXTRA_RESULT_HOST_NAME";
|
||||
public static final String EXTRA_RESULT_PORT = "EXTRA_RESULT_PORT";
|
||||
|
||||
private static final String TAG = "ScanResultActivity";
|
||||
|
||||
private KonfettiView konfettiView;
|
||||
private TextView descriptionText;
|
||||
@@ -39,6 +44,10 @@ public class ScanResultActivity extends LeanbackActivity {
|
||||
private TextView emojiText;
|
||||
private String hostName;
|
||||
private int port;
|
||||
|
||||
// Thread pool for background network operations
|
||||
private ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
private Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
private final int ORANGE = Color.rgb(253, 104, 40);
|
||||
private final int[] COLORS = {Color.RED, Color.BLUE, Color.CYAN, Color.GREEN, Color.YELLOW, ORANGE};
|
||||
@@ -177,9 +186,18 @@ public class ScanResultActivity extends LeanbackActivity {
|
||||
konfettiView.start(party);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
// Shutdown the thread pool to prevent leaks
|
||||
if (executor != null && !executor.isShutdown()) {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
/** A color int , or Color.BLACK to clear */
|
||||
private void setHyperionColor(String hostName, int port, int color){
|
||||
new Thread(() -> {
|
||||
executor.execute(() -> {
|
||||
try {
|
||||
HyperionFlatBuffers hyperion = new HyperionFlatBuffers(hostName, port, 50);
|
||||
if (hyperion.isConnected()){
|
||||
@@ -191,9 +209,11 @@ public class ScanResultActivity extends LeanbackActivity {
|
||||
}
|
||||
hyperion.disconnect();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
Log.e(TAG, "Failed to set hyperion color: " + e.getMessage());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Unexpected error setting hyperion color: " + e.getMessage());
|
||||
}
|
||||
}).start();
|
||||
});
|
||||
}
|
||||
|
||||
/** [0 -255] */
|
||||
|
||||
+7
-3
@@ -119,11 +119,15 @@ internal class BasicSettingsStepFragment : SettingsStepBaseFragment() {
|
||||
val frameRateLabels = resources.getStringArray(CommonR.array.pref_list_framerate)
|
||||
val frameRateValues = resources.getStringArray(CommonR.array.pref_list_framerate_values)
|
||||
|
||||
val selectedCaptureRate = prefs.getString(CommonR.string.pref_key_framerate, "30")
|
||||
val storedCaptureRate = prefs.getString(CommonR.string.pref_key_framerate, "30") ?: "30"
|
||||
val selectedCaptureRate =
|
||||
if (frameRateValues.contains(storedCaptureRate)) storedCaptureRate else "30"
|
||||
|
||||
val captureRateDescription =
|
||||
if (prefs.contains(CommonR.string.pref_key_framerate)){
|
||||
frameRateLabels[frameRateValues.indexOf(selectedCaptureRate)]
|
||||
if (prefs.contains(CommonR.string.pref_key_framerate)
|
||||
&& frameRateValues.contains(storedCaptureRate)) {
|
||||
val idx = frameRateValues.indexOf(selectedCaptureRate)
|
||||
frameRateLabels[idx]
|
||||
} else {
|
||||
getString(CommonR.string.pref_summary_framerate)
|
||||
}
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ buildscript {
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:8.2.1'
|
||||
classpath 'com.android.tools.build:gradle:8.13.2'
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||
// NOTE: Do not place your application dependencies here; they belong
|
||||
// in the individual module build.gradle files
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" />
|
||||
|
||||
|
||||
@@ -6,12 +6,16 @@ import android.content.Intent;
|
||||
import android.media.projection.MediaProjectionManager;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.util.Log;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
import com.hyperion.grabber.common.util.MediaProjectionHelper;
|
||||
|
||||
public class BootActivity extends AppCompatActivity {
|
||||
public static final int REQUEST_MEDIA_PROJECTION = 1;
|
||||
private static final String TAG = "BootActivity";
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
|
||||
@Override
|
||||
@@ -20,7 +24,9 @@ public class BootActivity extends AppCompatActivity {
|
||||
MediaProjectionManager manager = (MediaProjectionManager)
|
||||
getSystemService(Context.MEDIA_PROJECTION_SERVICE);
|
||||
if (manager != null) {
|
||||
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
|
||||
Log.i(TAG, "Requesting MediaProjection permission");
|
||||
startActivityForResult(MediaProjectionHelper.createCaptureIntent(manager),
|
||||
REQUEST_MEDIA_PROJECTION);
|
||||
} else {
|
||||
finish();
|
||||
}
|
||||
@@ -31,7 +37,10 @@ public class BootActivity extends AppCompatActivity {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
if (requestCode == REQUEST_MEDIA_PROJECTION) {
|
||||
if (resultCode == Activity.RESULT_OK) {
|
||||
Log.i(TAG, "MediaProjection granted, starting service");
|
||||
startScreenRecorder(this, resultCode, data);
|
||||
} else {
|
||||
Log.w(TAG, "MediaProjection denied resultCode=" + resultCode);
|
||||
}
|
||||
finish();
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -68,18 +68,26 @@ abstract class HyperionScreenEncoderBase {
|
||||
}
|
||||
|
||||
public void clearLights() {
|
||||
new Thread(() -> {
|
||||
sleep(CLEAR_DELAY_MS);
|
||||
mListener.clear();
|
||||
}).start();
|
||||
// Use Handler instead of creating a new Thread - more efficient
|
||||
mHandler.postDelayed(() -> {
|
||||
try {
|
||||
mListener.clear();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error clearing lights: " + e.getMessage());
|
||||
}
|
||||
}, CLEAR_DELAY_MS);
|
||||
}
|
||||
|
||||
protected void clearAndDisconnect() {
|
||||
new Thread(() -> {
|
||||
sleep(CLEAR_DELAY_MS);
|
||||
mListener.clear();
|
||||
mListener.disconnect();
|
||||
}).start();
|
||||
// Use Handler instead of creating a new Thread - more efficient
|
||||
mHandler.postDelayed(() -> {
|
||||
try {
|
||||
mListener.clear();
|
||||
mListener.disconnect();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error clearing and disconnecting: " + e.getMessage());
|
||||
}
|
||||
}, CLEAR_DELAY_MS);
|
||||
}
|
||||
|
||||
private static void sleep(long ms) {
|
||||
|
||||
@@ -35,7 +35,7 @@ public class HyperionScreenService extends Service {
|
||||
public static final String BROADCAST_ERROR = "SERVICE_ERROR";
|
||||
public static final String BROADCAST_TAG = "SERVICE_STATUS";
|
||||
public static final String BROADCAST_FILTER = "SERVICE_FILTER";
|
||||
private static final boolean DEBUG = false;
|
||||
private static final boolean DEBUG = true;
|
||||
private static final String TAG = "HyperionScreenService";
|
||||
|
||||
private boolean mForegroundFailed = false;
|
||||
@@ -191,21 +191,22 @@ public class HyperionScreenService extends Service {
|
||||
if (mHyperionThread == null) {
|
||||
boolean isPrepared = prepared();
|
||||
if (isPrepared) {
|
||||
boolean foregroundStarted = tryStartForeground();
|
||||
tryStartForeground();
|
||||
acquireWakeLock();
|
||||
|
||||
if (!foregroundStarted) {
|
||||
acquireWakeLock();
|
||||
}
|
||||
mHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
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();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
|
||||
@@ -261,7 +262,7 @@ public class HyperionScreenService extends Service {
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
private boolean tryStartForeground() {
|
||||
private void tryStartForeground() {
|
||||
mForegroundFailed = false;
|
||||
|
||||
try {
|
||||
@@ -271,15 +272,20 @@ public class HyperionScreenService extends Service {
|
||||
} else {
|
||||
startForeground(NOTIFICATION_ID, getNotification());
|
||||
}
|
||||
return true;
|
||||
} catch (ForegroundServiceStartNotAllowedException e) {
|
||||
Log.e(TAG, "Foreground service start not allowed: " + e.getMessage());
|
||||
mForegroundFailed = true;
|
||||
mHandler.postDelayed(this::retryForegroundStart, 100);
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Foreground start failed: " + e.getMessage());
|
||||
mForegroundFailed = true;
|
||||
mHandler.postDelayed(this::retryForegroundStart, 100);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void retryForegroundStart() {
|
||||
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);
|
||||
@@ -287,14 +293,13 @@ public class HyperionScreenService extends Service {
|
||||
startForeground(NOTIFICATION_ID, getNotification());
|
||||
}
|
||||
mForegroundFailed = false;
|
||||
return true;
|
||||
if (DEBUG) Log.d(TAG, "Foreground start successful on retry");
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Foreground retry failed: " + e.getMessage());
|
||||
mForegroundFailed = true;
|
||||
notifyForegroundFailed();
|
||||
}
|
||||
}
|
||||
|
||||
notifyForegroundFailed();
|
||||
return false;
|
||||
}
|
||||
|
||||
private void acquireWakeLock() {
|
||||
@@ -371,29 +376,54 @@ public class HyperionScreenService extends Service {
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
private void startScreenRecord(final Intent intent) {
|
||||
if (DEBUG) Log.v(TAG, "Starting screen recorder");
|
||||
|
||||
if (mMediaProjectionManager == null) {
|
||||
Log.e(TAG, "MediaProjectionManager not initialized");
|
||||
mStartError = "Failed to initialize media projection manager";
|
||||
return;
|
||||
}
|
||||
|
||||
final int resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0);
|
||||
final MediaProjection projection = mMediaProjectionManager.getMediaProjection(resultCode, intent);
|
||||
WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
|
||||
|
||||
if (projection != null && window != null) {
|
||||
sMediaProjection = projection;
|
||||
final DisplayMetrics metrics = new DisplayMetrics();
|
||||
window.getDefaultDisplay().getRealMetrics(metrics);
|
||||
|
||||
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();
|
||||
if (projection == null) {
|
||||
Log.e(TAG, "Failed to create MediaProjection - permission may have been denied");
|
||||
mStartError = "Failed to obtain media projection";
|
||||
haltStartup();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
|
||||
if (window == null) {
|
||||
Log.e(TAG, "WindowManager not available");
|
||||
mStartError = "Failed to get window manager";
|
||||
projection.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
sMediaProjection = projection;
|
||||
final DisplayMetrics metrics = new DisplayMetrics();
|
||||
window.getDefaultDisplay().getRealMetrics(metrics);
|
||||
|
||||
Log.i(TAG, "MediaProjection OK screen=" + metrics.widthPixels + "x" + metrics.heightPixels
|
||||
+ " dpi=" + metrics.densityDpi
|
||||
+ " leds=" + mHorizontalLEDCount + "x" + mVerticalLEDCount
|
||||
+ " fps=" + mFrameRate);
|
||||
|
||||
HyperionGrabberOptions options = new HyperionGrabberOptions(
|
||||
mHorizontalLEDCount, mVerticalLEDCount, mFrameRate, mSendAverageColor);
|
||||
|
||||
Log.i(TAG, "Creating MediaCodec screen encoder");
|
||||
mHyperionEncoder = new HyperionScreenEncoder(
|
||||
mHyperionThread.getReceiver(),
|
||||
projection,
|
||||
metrics.widthPixels,
|
||||
metrics.heightPixels,
|
||||
metrics.densityDpi,
|
||||
options,
|
||||
this);
|
||||
mHyperionEncoder.sendStatus();
|
||||
}
|
||||
|
||||
private void stopScreenRecord() {
|
||||
if (DEBUG) Log.v(TAG, "Stopping screen recorder");
|
||||
|
||||
@@ -7,12 +7,16 @@ import android.content.Intent;
|
||||
import android.media.projection.MediaProjectionManager;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.util.Log;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
import com.hyperion.grabber.common.util.MediaProjectionHelper;
|
||||
|
||||
public class ToggleActivity extends AppCompatActivity {
|
||||
public static final int REQUEST_MEDIA_PROJECTION = 1;
|
||||
private static final String TAG = "ToggleActivity";
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
|
||||
@Override
|
||||
@@ -27,7 +31,6 @@ public class ToggleActivity extends AppCompatActivity {
|
||||
} else {
|
||||
requestPermission();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -35,11 +38,12 @@ public class ToggleActivity extends AppCompatActivity {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
if (requestCode == REQUEST_MEDIA_PROJECTION) {
|
||||
if (resultCode == Activity.RESULT_OK) {
|
||||
Log.i(TAG, "MediaProjection granted");
|
||||
startScreenRecorder(this, resultCode, data);
|
||||
} else {
|
||||
Log.w(TAG, "MediaProjection denied");
|
||||
}
|
||||
|
||||
finish();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,17 +83,17 @@ public class ToggleActivity extends AppCompatActivity {
|
||||
}
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
|
||||
private void requestPermission(){
|
||||
private void requestPermission() {
|
||||
MediaProjectionManager manager = (MediaProjectionManager)
|
||||
getSystemService(Context.MEDIA_PROJECTION_SERVICE);
|
||||
if (manager != null) {
|
||||
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
|
||||
Log.i(TAG, "Requesting MediaProjection permission");
|
||||
startActivityForResult(MediaProjectionHelper.createCaptureIntent(manager),
|
||||
REQUEST_MEDIA_PROJECTION);
|
||||
}
|
||||
}
|
||||
|
||||
/** stop recording & stop service */
|
||||
|
||||
private void stopService() {
|
||||
private void stopService() {
|
||||
Intent stopIntent = new Intent(ToggleActivity.this, HyperionScreenService.class);
|
||||
stopIntent.setAction(HyperionScreenService.ACTION_EXIT);
|
||||
startService(stopIntent);
|
||||
|
||||
@@ -25,43 +25,43 @@ class HyperionThread(
|
||||
private val reconnectEnabled = AtomicBoolean(reconnect)
|
||||
private val connected = AtomicBoolean(false)
|
||||
private val clientRef = AtomicReference<HyperionClient>()
|
||||
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
|
||||
private val networkExecutor: ExecutorService = Executors.newSingleThreadExecutor()
|
||||
|
||||
@Volatile
|
||||
private var pendingTask: Future<*>? = null
|
||||
|
||||
@Volatile
|
||||
private var pendingFrame: FrameData? = null
|
||||
private val latestFrame = AtomicReference<FrameData>()
|
||||
private var lastFrameNumber = 0L
|
||||
private var sendTaskScheduled = AtomicBoolean(false)
|
||||
|
||||
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)
|
||||
// Copy — encoder reuses the ring buffer; async send must not share it.
|
||||
val copy = data.copyOf()
|
||||
++lastFrameNumber
|
||||
latestFrame.set(FrameData(copy, width, height, lastFrameNumber))
|
||||
|
||||
if (sendTaskScheduled.compareAndSet(false, true)) {
|
||||
networkExecutor.submit { sendLatestFrame() }
|
||||
}
|
||||
|
||||
pendingTask = executor.submit { sendPendingFrame() }
|
||||
}
|
||||
|
||||
private fun sendPendingFrame() {
|
||||
val frame = pendingFrame
|
||||
val client = clientRef.get()
|
||||
|
||||
if (frame == null || client == null || !client.isConnected()) return
|
||||
|
||||
private fun sendLatestFrame() {
|
||||
try {
|
||||
client.setImage(frame.data, frame.width, frame.height, priority, FRAME_DURATION)
|
||||
val frame = latestFrame.getAndSet(null) ?: return
|
||||
val client = clientRef.get()
|
||||
|
||||
if (client is HyperionFlatBuffers) {
|
||||
client.cleanReplies()
|
||||
if (client != null && client.isConnected()) {
|
||||
client.setImage(frame.data, frame.width, frame.height, priority, FRAME_DURATION)
|
||||
|
||||
if (client is HyperionFlatBuffers) {
|
||||
client.cleanReplies()
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
handleError(e)
|
||||
} finally {
|
||||
sendTaskScheduled.set(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,17 +77,14 @@ class HyperionThread(
|
||||
}
|
||||
|
||||
override fun disconnect() {
|
||||
val pending = pendingTask
|
||||
if (pending != null) {
|
||||
pending.cancel(true)
|
||||
pendingTask = null
|
||||
}
|
||||
pendingFrame = null
|
||||
latestFrame.set(null)
|
||||
lastFrameNumber = 0
|
||||
sendTaskScheduled.set(false)
|
||||
|
||||
if (!executor.isShutdown) {
|
||||
executor.shutdownNow()
|
||||
if (!networkExecutor.isShutdown) {
|
||||
networkExecutor.shutdownNow()
|
||||
try {
|
||||
executor.awaitTermination(SHUTDOWN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS)
|
||||
networkExecutor.awaitTermination(SHUTDOWN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS)
|
||||
} catch (e: InterruptedException) {
|
||||
currentThread().interrupt()
|
||||
}
|
||||
@@ -113,17 +110,10 @@ class HyperionThread(
|
||||
connect()
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the current socket without shutting down the executor.
|
||||
* Call [resumeConnection] to reconnect (e.g. on screen wake).
|
||||
*/
|
||||
fun pauseConnection() {
|
||||
val pending = pendingTask
|
||||
if (pending != null) {
|
||||
pending.cancel(false)
|
||||
pendingTask = null
|
||||
}
|
||||
pendingFrame = null
|
||||
latestFrame.set(null)
|
||||
lastFrameNumber = 0
|
||||
sendTaskScheduled.set(false)
|
||||
val client = clientRef.getAndSet(null)
|
||||
if (client != null) {
|
||||
try { client.disconnect() } catch (ignored: IOException) {}
|
||||
@@ -131,13 +121,9 @@ class HyperionThread(
|
||||
connected.set(false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a fresh socket on the executor thread.
|
||||
* Call after [pauseConnection] when the screen wakes up.
|
||||
*/
|
||||
fun resumeConnection() {
|
||||
if (executor.isShutdown) return
|
||||
executor.submit {
|
||||
if (networkExecutor.isShutdown) return
|
||||
networkExecutor.submit {
|
||||
try {
|
||||
val client = createClient()
|
||||
if (client.isConnected()) {
|
||||
@@ -205,7 +191,7 @@ class HyperionThread(
|
||||
}
|
||||
}
|
||||
|
||||
private class FrameData(val data: ByteArray, val width: Int, val height: Int)
|
||||
private class FrameData(val data: ByteArray, val width: Int, val height: Int, val frameNumber: Long)
|
||||
|
||||
interface HyperionThreadListener {
|
||||
fun sendFrame(data: ByteArray, width: Int, height: Int)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.hyperion.grabber.common.util;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class AnimationSyncController {
|
||||
private static final int ANIMATION_PATTERN_LENGTH = 64;
|
||||
private static final int ANIMATION_CYCLE_MS = 1000;
|
||||
|
||||
private final AtomicLong startTimeNs = new AtomicLong(System.nanoTime());
|
||||
private final AtomicInteger frameDelay = new AtomicInteger(0);
|
||||
private final AtomicInteger animationIntensity = new AtomicInteger(0);
|
||||
private boolean animationEnabled = false;
|
||||
|
||||
public AnimationSyncController(int frameDelayMs, boolean enableAnimation) {
|
||||
this.frameDelay.set(frameDelayMs);
|
||||
this.animationEnabled = enableAnimation;
|
||||
this.startTimeNs.set(System.nanoTime());
|
||||
}
|
||||
|
||||
public void setFrameDelay(int delayMs) {
|
||||
frameDelay.set(Math.max(-100, Math.min(100, delayMs)));
|
||||
}
|
||||
|
||||
public void setAnimationEnabled(boolean enabled) {
|
||||
animationEnabled = enabled;
|
||||
if (enabled) {
|
||||
startTimeNs.set(System.nanoTime());
|
||||
}
|
||||
}
|
||||
|
||||
public int getAnimationIntensity() {
|
||||
if (!animationEnabled) return 0;
|
||||
|
||||
long elapsedMs = (System.nanoTime() - startTimeNs.get()) / 1_000_000L;
|
||||
int cyclePosition = (int)(elapsedMs % ANIMATION_CYCLE_MS);
|
||||
|
||||
int intensity;
|
||||
if (cyclePosition < ANIMATION_CYCLE_MS / 2) {
|
||||
intensity = (cyclePosition * 255) / (ANIMATION_CYCLE_MS / 2);
|
||||
} else {
|
||||
intensity = ((ANIMATION_CYCLE_MS - cyclePosition) * 255) / (ANIMATION_CYCLE_MS / 2);
|
||||
}
|
||||
|
||||
return intensity & 0xFF;
|
||||
}
|
||||
|
||||
public long getEffectiveFrameDelayNs() {
|
||||
return frameDelay.get() * 1_000_000L;
|
||||
}
|
||||
|
||||
public byte[] applyAnimationToFrame(byte[] frameData) {
|
||||
if (!animationEnabled || frameData == null || frameData.length == 0) {
|
||||
return frameData;
|
||||
}
|
||||
|
||||
int intensity = getAnimationIntensity();
|
||||
byte[] animatedFrame = frameData.clone();
|
||||
|
||||
int step = Math.max(1, animatedFrame.length / ANIMATION_PATTERN_LENGTH);
|
||||
for (int i = 0; i < animatedFrame.length; i += step) {
|
||||
int channel = i % 3;
|
||||
if (channel < 2) {
|
||||
int value = (animatedFrame[i] & 0xFF);
|
||||
int modulated = (value * intensity) / 255;
|
||||
animatedFrame[i] = (byte) modulated;
|
||||
}
|
||||
}
|
||||
|
||||
return animatedFrame;
|
||||
}
|
||||
|
||||
public void sleep(long frameIntervalMs) throws InterruptedException {
|
||||
long sleepTimeMs = Math.max(1, frameIntervalMs + frameDelay.get());
|
||||
Thread.sleep(sleepTimeMs);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package com.hyperion.grabber.common.util;
|
||||
|
||||
import android.media.AudioFormat;
|
||||
import android.media.AudioRecord;
|
||||
import android.media.MediaRecorder;
|
||||
import android.util.Log;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicIntegerArray;
|
||||
|
||||
public class AudioVisualizerController {
|
||||
private static final String TAG = "AudioVisualizer";
|
||||
private static final int SAMPLE_RATE = 16000;
|
||||
private static final int BUFFER_SIZE = 2048;
|
||||
private static final int SPECTRUM_BANDS = 64;
|
||||
|
||||
private AudioRecord audioRecord;
|
||||
private Thread captureThread;
|
||||
private final AtomicBoolean isCapturing = new AtomicBoolean(false);
|
||||
private final AtomicIntegerArray spectrumData = new AtomicIntegerArray(SPECTRUM_BANDS);
|
||||
private volatile int[] audioWaveform = new int[BUFFER_SIZE];
|
||||
|
||||
public AudioVisualizerController() {
|
||||
initAudioRecord();
|
||||
}
|
||||
|
||||
private void initAudioRecord() {
|
||||
try {
|
||||
int bufferSize = AudioRecord.getMinBufferSize(
|
||||
SAMPLE_RATE,
|
||||
AudioFormat.CHANNEL_IN_MONO,
|
||||
AudioFormat.ENCODING_PCM_16BIT);
|
||||
|
||||
audioRecord = new AudioRecord(
|
||||
MediaRecorder.AudioSource.MIC,
|
||||
SAMPLE_RATE,
|
||||
AudioFormat.CHANNEL_IN_MONO,
|
||||
AudioFormat.ENCODING_PCM_16BIT,
|
||||
Math.max(bufferSize, BUFFER_SIZE * 2));
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to initialize AudioRecord", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void start() {
|
||||
if (isCapturing.getAndSet(true)) return;
|
||||
if (audioRecord == null) return;
|
||||
|
||||
try {
|
||||
audioRecord.startRecording();
|
||||
captureThread = new Thread(this::captureAudio, "AudioCapture");
|
||||
captureThread.setDaemon(true);
|
||||
captureThread.start();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to start audio capture", e);
|
||||
isCapturing.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
if (!isCapturing.getAndSet(false)) return;
|
||||
|
||||
if (audioRecord != null) {
|
||||
try {
|
||||
audioRecord.stop();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error stopping audio record", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (captureThread != null) {
|
||||
try {
|
||||
captureThread.join(500);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void captureAudio() {
|
||||
if (audioRecord == null) return;
|
||||
|
||||
short[] buffer = new short[BUFFER_SIZE];
|
||||
|
||||
while (isCapturing.get()) {
|
||||
try {
|
||||
int readSize = audioRecord.read(buffer, 0, BUFFER_SIZE);
|
||||
if (readSize > 0) {
|
||||
processAudio(buffer, readSize);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error reading audio", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processAudio(short[] buffer, int size) {
|
||||
int[] waveform = new int[size];
|
||||
for (int i = 0; i < size; i++) {
|
||||
waveform[i] = Math.abs(buffer[i]);
|
||||
}
|
||||
audioWaveform = waveform;
|
||||
|
||||
computeSpectrum(buffer, size);
|
||||
}
|
||||
|
||||
private void computeSpectrum(short[] buffer, int size) {
|
||||
int[] spectrum = new int[SPECTRUM_BANDS];
|
||||
|
||||
for (int band = 0; band < SPECTRUM_BANDS; band++) {
|
||||
int bandWidth = size / SPECTRUM_BANDS;
|
||||
int startIdx = band * bandWidth;
|
||||
int endIdx = startIdx + bandWidth;
|
||||
|
||||
long sum = 0;
|
||||
for (int i = startIdx; i < endIdx && i < size; i++) {
|
||||
sum += Math.abs(buffer[i]);
|
||||
}
|
||||
|
||||
int avgMagnitude = (int) (sum / bandWidth);
|
||||
spectrum[band] = Math.min(255, avgMagnitude / 128);
|
||||
}
|
||||
|
||||
for (int i = 0; i < SPECTRUM_BANDS; i++) {
|
||||
spectrumData.set(i, spectrum[i]);
|
||||
}
|
||||
}
|
||||
|
||||
public int getSpectrumBand(int band) {
|
||||
if (band < 0 || band >= SPECTRUM_BANDS) return 0;
|
||||
return spectrumData.get(band);
|
||||
}
|
||||
|
||||
public int[] getFullSpectrum() {
|
||||
int[] result = new int[SPECTRUM_BANDS];
|
||||
for (int i = 0; i < SPECTRUM_BANDS; i++) {
|
||||
result[i] = spectrumData.get(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public int[] getWaveform() {
|
||||
return audioWaveform;
|
||||
}
|
||||
|
||||
public int getWaveformSample(int index) {
|
||||
if (index < 0 || index >= audioWaveform.length) return 0;
|
||||
return audioWaveform[index];
|
||||
}
|
||||
|
||||
public void release() {
|
||||
stop();
|
||||
if (audioRecord != null) {
|
||||
try {
|
||||
audioRecord.release();
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error releasing audio record", e);
|
||||
}
|
||||
audioRecord = null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isCapturing() {
|
||||
return isCapturing.get();
|
||||
}
|
||||
|
||||
public static int[] generateAudioVisualization(int width, int height, int[] spectrum) {
|
||||
int[] visualization = new int[width * height * 3];
|
||||
int bandWidth = Math.max(1, width / spectrum.length);
|
||||
|
||||
for (int y = 0; y < height; y++) {
|
||||
for (int x = 0; x < width; x++) {
|
||||
int band = Math.min(x / bandWidth, spectrum.length - 1);
|
||||
int intensity = spectrum[band];
|
||||
|
||||
float normalizedHeight = (float) y / height;
|
||||
int value = (int) (intensity * (1.0f - normalizedHeight));
|
||||
|
||||
int idx = (y * width + x) * 3;
|
||||
visualization[idx] = Math.min(255, value);
|
||||
visualization[idx + 1] = Math.min(255, value * 2 / 3);
|
||||
visualization[idx + 2] = Math.min(255, value / 2);
|
||||
}
|
||||
}
|
||||
|
||||
return visualization;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.hyperion.grabber.common.util;
|
||||
|
||||
import android.util.Log;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
/**
|
||||
* Object pool for byte arrays to reduce garbage collection pressure
|
||||
* Reuses allocated buffers instead of creating new ones
|
||||
*/
|
||||
public class BufferPool {
|
||||
private static final String TAG = "BufferPool";
|
||||
private static BufferPool instance;
|
||||
|
||||
private final ConcurrentLinkedQueue<byte[]> pool = new ConcurrentLinkedQueue<>();
|
||||
private final int bufferSize;
|
||||
private final int maxPoolSize;
|
||||
private int poolHits = 0;
|
||||
private int poolMisses = 0;
|
||||
|
||||
private BufferPool(int bufferSize, int maxPoolSize) {
|
||||
this.bufferSize = bufferSize;
|
||||
this.maxPoolSize = maxPoolSize;
|
||||
Log.d(TAG, "BufferPool initialized: size=" + bufferSize + " bytes, max=" + maxPoolSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create singleton with specified buffer size
|
||||
*/
|
||||
public static synchronized BufferPool getInstance(int bufferSize, int maxPoolSize) {
|
||||
if (instance == null) {
|
||||
instance = new BufferPool(bufferSize, maxPoolSize);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquire a buffer from the pool or create a new one
|
||||
*/
|
||||
public byte[] acquire() {
|
||||
byte[] buffer = pool.poll();
|
||||
if (buffer != null) {
|
||||
poolHits++;
|
||||
if (poolHits % 100 == 0) {
|
||||
Log.d(TAG, "Pool stats - Hits: " + poolHits + ", Misses: " + poolMisses);
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
poolMisses++;
|
||||
return new byte[bufferSize];
|
||||
}
|
||||
|
||||
/**
|
||||
* Release a buffer back to the pool
|
||||
*/
|
||||
public void release(byte[] buffer) {
|
||||
if (buffer != null && buffer.length == bufferSize && pool.size() < maxPoolSize) {
|
||||
pool.offer(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the pool
|
||||
*/
|
||||
public void clear() {
|
||||
pool.clear();
|
||||
Log.d(TAG, "BufferPool cleared");
|
||||
}
|
||||
|
||||
/**
|
||||
* Get pool statistics
|
||||
*/
|
||||
public String getStats() {
|
||||
return "BufferPool stats: Size=" + pool.size() +
|
||||
", Hits=" + poolHits + ", Misses=" + poolMisses +
|
||||
", HitRate=" + String.format("%.2f%%",
|
||||
(poolHits * 100.0) / (poolHits + poolMisses));
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.hyperion.grabber.common.util;
|
||||
|
||||
import android.util.Log;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
@@ -66,19 +67,42 @@ public class HyperionGrabberOptions {
|
||||
|
||||
/**
|
||||
* gets a list of all the common divisors [large to small] for the given integers.
|
||||
* Uses GCD-based approach for O(log n) complexity instead of O(n).
|
||||
* @param num1 The first integer to find a whole number divisor for
|
||||
* @param num2 The second integer to find a whole number divisor for
|
||||
* @return List A list of the common divisors [large to small] that match the provided integers
|
||||
**/
|
||||
private static List<Integer> getCommonDivisors(int num1, int num2) {
|
||||
List<Integer> list = new ArrayList<>();
|
||||
int min = Math.min(num1, num2);
|
||||
for (int i = 1; i <= min / 2; i++)
|
||||
if (num1 % i == 0 && num2 % i == 0)
|
||||
int gcd = gcd(num1, num2);
|
||||
|
||||
// Find all divisors of the GCD (much more efficient than checking all numbers up to min/2)
|
||||
int limit = (int) Math.sqrt(gcd);
|
||||
for (int i = 1; i <= limit; i++) {
|
||||
if (gcd % i == 0) {
|
||||
list.add(i);
|
||||
if (num1 % min == 0 && num2 % min == 0) list.add(min);
|
||||
if (i != gcd / i) {
|
||||
list.add(gcd / i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort in ascending order so we can iterate backwards efficiently
|
||||
java.util.Collections.sort(list);
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute GCD using Euclidean algorithm - much more efficient than checking all divisors
|
||||
*/
|
||||
private static int gcd(int a, int b) {
|
||||
while (b != 0) {
|
||||
int temp = b;
|
||||
b = a % b;
|
||||
a = temp;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
public int getBlackThreshold() { return BLACK_THRESHOLD; }
|
||||
}
|
||||
@@ -31,6 +31,16 @@ public class HyperionScannerTask {
|
||||
mainHandler.post(() -> onPostExecute(result));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Shutdown the executor service to prevent thread leaks
|
||||
* Call this when you no longer need the scanner
|
||||
*/
|
||||
public void shutdown() {
|
||||
if (executor != null && !executor.isShutdown()) {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
private String doInBackground() {
|
||||
Log.d("Hyperion scanner", "starting scan");
|
||||
@@ -53,15 +63,19 @@ public class HyperionScannerTask {
|
||||
|
||||
private void onProgressUpdate(Float value) {
|
||||
Log.d("Hyperion scanner", "scan progress: " + value);
|
||||
if(weakListener.get() != null){
|
||||
weakListener.get().onScannerProgress(value);
|
||||
// Cache the listener reference to avoid multiple get() calls
|
||||
Listener listener = weakListener.get();
|
||||
if (listener != null) {
|
||||
listener.onScannerProgress(value);
|
||||
}
|
||||
}
|
||||
|
||||
private void onPostExecute(String result) {
|
||||
Log.d("Hyperion scanner", "scan result: " + result);
|
||||
if(weakListener.get() != null){
|
||||
weakListener.get().onScannerCompleted(result);
|
||||
// Cache the listener reference to avoid multiple get() calls
|
||||
Listener listener = weakListener.get();
|
||||
if (listener != null) {
|
||||
listener.onScannerCompleted(result);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.hyperion.grabber.common.util;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.media.projection.MediaProjectionConfig;
|
||||
import android.media.projection.MediaProjectionManager;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
/**
|
||||
* Creates MediaProjection consent intents. On Android 14+ prefers
|
||||
* {@link MediaProjectionConfig#createConfigForDefaultDisplay()} so the entire
|
||||
* display is captured (not only an app window).
|
||||
*/
|
||||
public final class MediaProjectionHelper {
|
||||
private static final String TAG = "MediaProjectionHelper";
|
||||
|
||||
private MediaProjectionHelper() {}
|
||||
|
||||
public static Intent createCaptureIntent(MediaProjectionManager manager) {
|
||||
if (manager == null) {
|
||||
throw new IllegalArgumentException("MediaProjectionManager is null");
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
try {
|
||||
MediaProjectionConfig config =
|
||||
MediaProjectionConfig.createConfigForDefaultDisplay();
|
||||
Log.i(TAG, "Using MediaProjectionConfig.createConfigForDefaultDisplay()");
|
||||
return manager.createScreenCaptureIntent(config);
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "Default-display config failed, falling back: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
Log.i(TAG, "Using default createScreenCaptureIntent()");
|
||||
return manager.createScreenCaptureIntent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.hyperion.grabber.common.util;
|
||||
|
||||
import android.util.Log;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Performance monitoring utility for tracking operation metrics
|
||||
* Helps identify bottlenecks and performance regressions
|
||||
*/
|
||||
public class PerformanceMonitor {
|
||||
private static final String TAG = "PerformanceMonitor";
|
||||
private static final boolean DEBUG = false;
|
||||
|
||||
private static class Metric {
|
||||
long count = 0;
|
||||
long totalTime = 0;
|
||||
long maxTime = 0;
|
||||
long minTime = Long.MAX_VALUE;
|
||||
|
||||
void record(long duration) {
|
||||
count++;
|
||||
totalTime += duration;
|
||||
maxTime = Math.max(maxTime, duration);
|
||||
minTime = Math.min(minTime, duration);
|
||||
}
|
||||
|
||||
double getAverage() {
|
||||
return count > 0 ? (double) totalTime / count : 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static final ConcurrentHashMap<String, Metric> metrics = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Start timing an operation
|
||||
*/
|
||||
public static long startTimer() {
|
||||
return System.nanoTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* End timing and record metric
|
||||
*/
|
||||
public static void recordMetric(String name, long startTime) {
|
||||
long duration = System.nanoTime() - startTime;
|
||||
Metric metric = metrics.computeIfAbsent(name, k -> new Metric());
|
||||
metric.record(duration);
|
||||
|
||||
if (DEBUG && metric.count % 100 == 0) {
|
||||
Log.d(TAG, String.format("%s - Avg: %.2fms, Max: %dms, Min: %dms, Count: %d",
|
||||
name,
|
||||
metric.getAverage() / 1_000_000.0,
|
||||
metric.maxTime / 1_000_000,
|
||||
metric.minTime / 1_000_000,
|
||||
metric.count));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get metric statistics
|
||||
*/
|
||||
public static String getMetrics(String name) {
|
||||
Metric metric = metrics.get(name);
|
||||
if (metric == null) return "No metrics for: " + name;
|
||||
|
||||
return String.format("%s - Average: %.2fms, Max: %dms, Min: %dms, Count: %d, Total: %.2fs",
|
||||
name,
|
||||
metric.getAverage() / 1_000_000.0,
|
||||
metric.maxTime / 1_000_000,
|
||||
metric.minTime / 1_000_000,
|
||||
metric.count,
|
||||
metric.totalTime / 1_000_000_000.0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all metrics
|
||||
*/
|
||||
public static void clearAll() {
|
||||
metrics.clear();
|
||||
Log.d(TAG, "All metrics cleared");
|
||||
}
|
||||
|
||||
/**
|
||||
* Print all metrics
|
||||
*/
|
||||
public static void printAll() {
|
||||
Log.d(TAG, "=== Performance Metrics ===");
|
||||
for (String name : metrics.keySet()) {
|
||||
Log.d(TAG, getMetrics(name));
|
||||
}
|
||||
Log.d(TAG, "=========================");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package com.hyperion.grabber.common.util;
|
||||
|
||||
import android.app.ActivityManager;
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
/**
|
||||
* Performance optimizer utility providing device-aware optimizations
|
||||
* Adapts behavior based on available system resources
|
||||
*/
|
||||
public class PerformanceOptimizer {
|
||||
private static final String TAG = "PerformanceOptimizer";
|
||||
private static PerformanceOptimizer instance;
|
||||
|
||||
private final Context context;
|
||||
private final ActivityManager activityManager;
|
||||
private final boolean isLowMemoryDevice;
|
||||
private final int availableMemoryMb;
|
||||
|
||||
private PerformanceOptimizer(Context context) {
|
||||
this.context = context.getApplicationContext();
|
||||
this.activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
|
||||
this.availableMemoryMb = getAvailableMemory();
|
||||
this.isLowMemoryDevice = availableMemoryMb < 1024; // Less than 1GB
|
||||
|
||||
Log.d(TAG, "Device memory: " + availableMemoryMb + "MB, Low memory device: " + isLowMemoryDevice);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get singleton instance
|
||||
*/
|
||||
public static synchronized PerformanceOptimizer getInstance(Context context) {
|
||||
if (instance == null) {
|
||||
instance = new PerformanceOptimizer(context);
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get available system memory in MB
|
||||
*/
|
||||
private int getAvailableMemory() {
|
||||
try {
|
||||
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
|
||||
if (activityManager != null) {
|
||||
activityManager.getMemoryInfo(memInfo);
|
||||
return (int) (memInfo.totalMem / 1048576L); // Convert to MB
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Failed to get memory info: " + e.getMessage());
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get optimized frame rate based on device capabilities
|
||||
* Higher end devices can handle higher frame rates
|
||||
*/
|
||||
public int getOptimizedFrameRate(int requestedFrameRate) {
|
||||
if (isLowMemoryDevice) {
|
||||
// Cap at 30fps for low memory devices
|
||||
return Math.min(requestedFrameRate, 30);
|
||||
} else if (availableMemoryMb < 2048) {
|
||||
// Cap at 45fps for mid-range devices
|
||||
return Math.min(requestedFrameRate, 45);
|
||||
}
|
||||
// No limit for high-end devices
|
||||
return requestedFrameRate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get optimized buffer size based on device memory
|
||||
* Prevents OOM on low-memory devices
|
||||
*/
|
||||
public int getOptimizedBufferSize(int baseSize) {
|
||||
if (isLowMemoryDevice) {
|
||||
// Use 75% of base size on low memory devices
|
||||
return (baseSize * 3) / 4;
|
||||
} else if (availableMemoryMb < 2048) {
|
||||
// Use 90% of base size on mid-range devices
|
||||
return (baseSize * 9) / 10;
|
||||
}
|
||||
// Use full size on high-end devices
|
||||
return baseSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if aggressive garbage collection should be enabled
|
||||
*/
|
||||
public boolean shouldUseAggressiveGC() {
|
||||
return isLowMemoryDevice;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get thread pool size recommendation
|
||||
*/
|
||||
public int getOptimalThreadPoolSize() {
|
||||
int processors = Runtime.getRuntime().availableProcessors();
|
||||
if (isLowMemoryDevice) {
|
||||
// Use single thread on low memory devices
|
||||
return 1;
|
||||
} else if (availableMemoryMb < 2048) {
|
||||
// Use min(2, processors) on mid-range
|
||||
return Math.min(2, processors);
|
||||
}
|
||||
// Use processors/2 + 1 on high-end (standard formula)
|
||||
return Math.max(processors / 2 + 1, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if device has enough memory for high-quality operations
|
||||
*/
|
||||
public boolean hasEnoughMemoryForHighQuality() {
|
||||
return availableMemoryMb >= 2048;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get memory cache size in MB
|
||||
*/
|
||||
public int getMemoryCacheSize() {
|
||||
if (isLowMemoryDevice) {
|
||||
return 2; // 2MB for low memory devices
|
||||
} else if (availableMemoryMb < 2048) {
|
||||
return 5; // 5MB for mid-range
|
||||
}
|
||||
return 10; // 10MB for high-end
|
||||
}
|
||||
|
||||
public boolean isLowMemoryDevice() {
|
||||
return isLowMemoryDevice;
|
||||
}
|
||||
|
||||
public int getAvailableMemoryMb() {
|
||||
return availableMemoryMb;
|
||||
}
|
||||
}
|
||||
@@ -4,30 +4,57 @@ import android.content.Context
|
||||
import android.content.res.Resources
|
||||
import androidx.preference.PreferenceManager
|
||||
import androidx.annotation.StringRes
|
||||
import android.util.Log
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/** Wrapper around SharedPreferences which allows for default values defined in Resources
|
||||
* Main purpose is that defaults are defined in a centralized location and that preferences are
|
||||
* accessed through a unified interface */
|
||||
/** Wrapper around SharedPreferences with defaults from Resources and an in-memory cache. */
|
||||
class Preferences(context: Context) {
|
||||
|
||||
private val preferences = PreferenceManager.getDefaultSharedPreferences(context)
|
||||
private val resources = context.resources
|
||||
|
||||
// ConcurrentHashMap forbids null values — never store nulls.
|
||||
private val stringCache = ConcurrentHashMap<String, String>()
|
||||
private val intCache = ConcurrentHashMap<String, Int>()
|
||||
private val boolCache = ConcurrentHashMap<String, Boolean>()
|
||||
private val nullStringKeys = ConcurrentHashMap.newKeySet<String>()
|
||||
|
||||
fun contains(@StringRes keyResourceId: Int): Boolean = preferences.contains(key(keyResourceId))
|
||||
|
||||
fun getString(@StringRes keyResourceId: Int, default: String? = null): String? {
|
||||
return preferences.getString(key(keyResourceId), default)
|
||||
val keyStr = key(keyResourceId)
|
||||
|
||||
if (nullStringKeys.contains(keyStr)) {
|
||||
return default
|
||||
}
|
||||
stringCache[keyStr]?.let { return it }
|
||||
|
||||
val value = preferences.getString(keyStr, default)
|
||||
if (value != null) {
|
||||
stringCache[keyStr] = value
|
||||
nullStringKeys.remove(keyStr)
|
||||
} else {
|
||||
stringCache.remove(keyStr)
|
||||
nullStringKeys.add(keyStr)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
fun putString(@StringRes keyResourceId: Int, value: String){
|
||||
val edit = preferences.edit()
|
||||
edit.putString(key(keyResourceId), value)
|
||||
edit.apply()
|
||||
fun putString(@StringRes keyResourceId: Int, value: String) {
|
||||
val keyStr = key(keyResourceId)
|
||||
preferences.edit().putString(keyStr, value).apply()
|
||||
stringCache[keyStr] = value
|
||||
nullStringKeys.remove(keyStr)
|
||||
intCache.remove(keyStr)
|
||||
boolCache.remove(keyStr)
|
||||
}
|
||||
|
||||
fun getInt(@StringRes keyResourceId: Int): Int {
|
||||
val keyStr = key(keyResourceId)
|
||||
intCache[keyStr]?.let { return it }
|
||||
|
||||
val default = defaultKey(keyResourceId, "integer").let {
|
||||
if (it == 0){
|
||||
if (it == 0) {
|
||||
0
|
||||
} else {
|
||||
try {
|
||||
@@ -42,16 +69,31 @@ class Preferences(context: Context) {
|
||||
}
|
||||
|
||||
fun getInt(@StringRes keyResourceId: Int, default: Int = 0): Int {
|
||||
return getString(keyResourceId)?.let { Integer.parseInt(it) } ?: default
|
||||
val keyStr = key(keyResourceId)
|
||||
intCache[keyStr]?.let { return it }
|
||||
|
||||
val raw = getString(keyResourceId)
|
||||
val value = try {
|
||||
if (raw.isNullOrBlank()) default else Integer.parseInt(raw.trim())
|
||||
} catch (e: NumberFormatException) {
|
||||
Log.w("Preferences", "Invalid int for $keyStr: '$raw', using default $default")
|
||||
default
|
||||
}
|
||||
intCache[keyStr] = value
|
||||
return value
|
||||
}
|
||||
|
||||
fun putInt(@StringRes keyResourceId: Int, value: Int){
|
||||
fun putInt(@StringRes keyResourceId: Int, value: Int) {
|
||||
putString(keyResourceId, value.toString())
|
||||
intCache[key(keyResourceId)] = value
|
||||
}
|
||||
|
||||
fun getBoolean(@StringRes keyResourceId: Int): Boolean {
|
||||
val keyStr = key(keyResourceId)
|
||||
boolCache[keyStr]?.let { return it }
|
||||
|
||||
val default = defaultKey(keyResourceId, "bool").let {
|
||||
if (it == 0){
|
||||
if (it == 0) {
|
||||
false
|
||||
} else {
|
||||
try {
|
||||
@@ -62,24 +104,46 @@ class Preferences(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
return preferences.getBoolean(key(keyResourceId), default)
|
||||
val value = preferences.getBoolean(keyStr, default)
|
||||
boolCache[keyStr] = value
|
||||
return value
|
||||
}
|
||||
|
||||
fun getBoolean(@StringRes keyResourceId: Int, default: Boolean): Boolean =
|
||||
preferences.getBoolean(key(keyResourceId), default)
|
||||
fun getBoolean(@StringRes keyResourceId: Int, default: Boolean): Boolean {
|
||||
val keyStr = key(keyResourceId)
|
||||
boolCache[keyStr]?.let { return it }
|
||||
|
||||
fun putBoolean(@StringRes keyResourceId: Int, value: Boolean){
|
||||
val edit = preferences.edit()
|
||||
edit.putBoolean(key(keyResourceId), value)
|
||||
edit.apply()
|
||||
val value = preferences.getBoolean(keyStr, default)
|
||||
boolCache[keyStr] = value
|
||||
return value
|
||||
}
|
||||
|
||||
fun putBoolean(@StringRes keyResourceId: Int, value: Boolean) {
|
||||
val keyStr = key(keyResourceId)
|
||||
preferences.edit().putBoolean(keyStr, value).apply()
|
||||
boolCache[keyStr] = value
|
||||
stringCache.remove(keyStr)
|
||||
nullStringKeys.remove(keyStr)
|
||||
intCache.remove(keyStr)
|
||||
}
|
||||
|
||||
fun clearCache() {
|
||||
stringCache.clear()
|
||||
intCache.clear()
|
||||
boolCache.clear()
|
||||
nullStringKeys.clear()
|
||||
Log.d("Preferences", "Cache cleared")
|
||||
}
|
||||
|
||||
private fun key(keyResourceId: Int) = resources.getString(keyResourceId)
|
||||
|
||||
/** @return 0 if not found, resource id otherwise */
|
||||
private fun defaultKey(keyResourceId: Int, type: String): Int {
|
||||
val defaultKeyName = resources.getResourceEntryName(keyResourceId).replace("pref_key_", "pref_default_")
|
||||
return resources.getIdentifier(defaultKeyName, type, resources.getResourcePackageName(keyResourceId))
|
||||
val defaultKeyName = resources.getResourceEntryName(keyResourceId)
|
||||
.replace("pref_key_", "pref_default_")
|
||||
return resources.getIdentifier(
|
||||
defaultKeyName,
|
||||
type,
|
||||
resources.getResourcePackageName(keyResourceId)
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.hyperion.grabber.common.util;
|
||||
|
||||
import android.util.Log;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/**
|
||||
* Manages lifecycle of resources to ensure proper cleanup
|
||||
* Prevents resource leaks and improves application stability
|
||||
*/
|
||||
public class ResourceManager {
|
||||
private static final String TAG = "ResourceManager";
|
||||
|
||||
private final CopyOnWriteArrayList<Resource> resources = new CopyOnWriteArrayList<>();
|
||||
|
||||
/**
|
||||
* Register a resource for lifecycle management
|
||||
*/
|
||||
public void register(Resource resource) {
|
||||
if (resource != null) {
|
||||
resources.add(resource);
|
||||
Log.d(TAG, "Resource registered: " + resource.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister a resource
|
||||
*/
|
||||
public void unregister(Resource resource) {
|
||||
if (resources.remove(resource)) {
|
||||
Log.d(TAG, "Resource unregistered: " + resource.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Release all managed resources
|
||||
*/
|
||||
public void releaseAll() {
|
||||
for (Resource resource : resources) {
|
||||
try {
|
||||
resource.release();
|
||||
Log.d(TAG, "Resource released: " + resource.getClass().getSimpleName());
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Error releasing resource: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
resources.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get count of managed resources
|
||||
*/
|
||||
public int getResourceCount() {
|
||||
return resources.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resource interface for lifecycle management
|
||||
*/
|
||||
public interface Resource {
|
||||
/**
|
||||
* Called when resource should be released
|
||||
*/
|
||||
void release();
|
||||
}
|
||||
}
|
||||
@@ -39,4 +39,13 @@
|
||||
|
||||
<string name="pref_key_use_avg_color" translatable="false">pref_key_use_avg_color</string>
|
||||
<bool name="pref_default_use_avg_color" translatable="false">false</bool>
|
||||
|
||||
<string name="pref_key_frame_delay" translatable="false">pref_key_frame_delay</string>
|
||||
<integer name="pref_default_frame_delay" translatable="false">0</integer>
|
||||
|
||||
<string name="pref_key_enable_animation" translatable="false">pref_key_enable_animation</string>
|
||||
<bool name="pref_default_enable_animation" translatable="false">false</bool>
|
||||
|
||||
<string name="pref_key_audio_only_mode" translatable="false">pref_key_audio_only_mode</string>
|
||||
<bool name="pref_default_audio_only_mode" translatable="false">false</bool>
|
||||
</resources>
|
||||
@@ -70,6 +70,13 @@
|
||||
<string name="error_no_host_name_extra">That\'s weird, expected a hostname here</string>
|
||||
<string name="notification_channel_label">Hyperion Grabber Notifications</string>
|
||||
<string name="notification_description">Currently grabbing screen content</string>
|
||||
<string name="pref_title_use_avg_color">Send Average Screen Color</string>
|
||||
<string name="pref_summary_use_avg_color">Sends the average color of your device\'s screen rather than an image of it</string>
|
||||
<string name="pref_title_use_avg_color">Send Average Screen Color</string>
|
||||
<string name="pref_summary_use_avg_color">Sends the average color of your device\'s screen rather than an image of it</string>
|
||||
<string name="pref_group_sync">Synchronization</string>
|
||||
<string name="pref_title_frame_delay">Frame Delay</string>
|
||||
<string name="pref_summary_frame_delay">Delay frame updates in milliseconds to sync with RGB devices (-100 to +100ms)</string>
|
||||
<string name="pref_title_enable_animation">Enable Update Animation</string>
|
||||
<string name="pref_summary_enable_animation">Sends a synchronized animation pattern to help align RGB timing</string>
|
||||
<string name="pref_title_audio_only_mode">Audio Visualization Mode</string>
|
||||
<string name="pref_summary_audio_only_mode">Capture internal audio and visualize as gradient with audio-reactive sections</string>
|
||||
</resources>
|
||||
@@ -120,6 +120,34 @@
|
||||
|
||||
</PreferenceCategory>
|
||||
|
||||
<PreferenceCategory
|
||||
android:title="@string/pref_group_sync">
|
||||
|
||||
<EditTextPreference
|
||||
android:defaultValue="@integer/pref_default_frame_delay"
|
||||
android:hint="0"
|
||||
android:maxLines="1"
|
||||
android:key="@string/pref_key_frame_delay"
|
||||
android:summary="@string/pref_summary_frame_delay"
|
||||
android:numeric="integer"
|
||||
android:selectAllOnFocus="true"
|
||||
android:singleLine="true"
|
||||
android:title="@string/pref_title_frame_delay" />
|
||||
|
||||
<CheckBoxPreference
|
||||
android:defaultValue="@bool/pref_default_enable_animation"
|
||||
android:key="@string/pref_key_enable_animation"
|
||||
android:title="@string/pref_title_enable_animation"
|
||||
android:summary="@string/pref_summary_enable_animation" />
|
||||
|
||||
<CheckBoxPreference
|
||||
android:defaultValue="@bool/pref_default_audio_only_mode"
|
||||
android:key="@string/pref_key_audio_only_mode"
|
||||
android:title="@string/pref_title_audio_only_mode"
|
||||
android:summary="@string/pref_summary_audio_only_mode" />
|
||||
|
||||
</PreferenceCategory>
|
||||
|
||||
<PreferenceCategory
|
||||
android:title="@string/pref_group_general">
|
||||
|
||||
|
||||
Binary file not shown.
+1
-1
@@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip
|
||||
Reference in new issue
Block a user