Replace ImageReader capture with MediaCodec encode/decode for Amlogic.
Android CI / build (push) Canceled after 0s

Fixes black frames on Ugoos X5M Pro, stabilizes Home/resume, settings framerate crash, and ships a debug APK under dist/apk.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
robinandCursor committed 2026-07-19 14:52:46 +02:00
1 parent b9cbbfa13d
commit 063a068620
17 files changed
+884 -395

No files matched your search

+9
View File
@@ -5,6 +5,15 @@
# [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
+36
View File
@@ -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)
+64 -13
View File
@@ -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
View File
@@ -13,8 +13,8 @@ android {
applicationId "com.hyperion.grabber"
minSdk 21
targetSdk 34
versionCode 3000
versionName "3.0.0"
versionCode 3001
versionName "3.0.1-mediacodec"
}
buildTypes {
@@ -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,
@@ -151,7 +152,8 @@ public class MainActivity extends AppCompatActivity implements ImageView.OnClick
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 (SecurityException e) {
Log.e(TAG, "Screen capture permission denied: " + e.getMessage());
@@ -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)
@@ -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
View File
@@ -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
@@ -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
@@ -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;
@@ -405,10 +405,15 @@ public class HyperionScreenService extends Service {
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);
if (DEBUG) Log.v(TAG, "Creating encoder: " + metrics.widthPixels + "x" + metrics.heightPixels);
Log.i(TAG, "Creating MediaCodec screen encoder");
mHyperionEncoder = new HyperionScreenEncoder(
mHyperionThread.getReceiver(),
projection,
@@ -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();
}
}
@@ -83,12 +87,12 @@ public class ToggleActivity 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);
}
}
/** stop recording & stop service */
private void stopService() {
Intent stopIntent = new Intent(ToggleActivity.this, HyperionScreenService.class);
stopIntent.setAction(HyperionScreenService.ACTION_EXIT);
@@ -36,8 +36,10 @@ class HyperionThread(
val client = clientRef.get()
if (client == null || !client.isConnected()) return
// Copy — encoder reuses the ring buffer; async send must not share it.
val copy = data.copyOf()
++lastFrameNumber
latestFrame.set(FrameData(data, width, height, lastFrameNumber))
latestFrame.set(FrameData(copy, width, height, lastFrameNumber))
if (sendTaskScheduled.compareAndSet(false, true)) {
networkExecutor.submit { sendLatestFrame() }
@@ -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();
}
}
@@ -7,56 +7,51 @@ 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
* Now includes in-memory caching to reduce disk I/O */
/** 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
// In-memory cache to reduce SharedPreferences disk I/O
private val stringCache = ConcurrentHashMap<String, String?>()
// 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 cacheHits = 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? {
val keyStr = key(keyResourceId)
// Return from cache if available
if (stringCache.containsKey(keyStr)) {
return stringCache[keyStr]
if (nullStringKeys.contains(keyStr)) {
return default
}
stringCache[keyStr]?.let { return it }
// Fetch from SharedPreferences and cache
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 keyStr = key(keyResourceId)
val edit = preferences.edit()
edit.putString(keyStr, value)
edit.apply()
// Update cache
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)
// Return from cache if available
if (intCache.containsKey(keyStr)) {
return intCache[keyStr]!!
}
intCache[keyStr]?.let { return it }
val default = defaultKey(keyResourceId, "integer").let {
if (it == 0) {
@@ -75,30 +70,27 @@ class Preferences(context: Context) {
fun getInt(@StringRes keyResourceId: Int, default: Int = 0): Int {
val keyStr = key(keyResourceId)
intCache[keyStr]?.let { return it }
// Return from cache if available
if (intCache.containsKey(keyStr)) {
return intCache[keyStr]!!
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
}
val value = getString(keyResourceId)?.let { Integer.parseInt(it) } ?: default
intCache[keyStr] = value
return value
}
fun putInt(@StringRes keyResourceId: Int, value: Int) {
putString(keyResourceId, value.toString())
val keyStr = key(keyResourceId)
intCache[keyStr] = value
intCache[key(keyResourceId)] = value
}
fun getBoolean(@StringRes keyResourceId: Int): Boolean {
val keyStr = key(keyResourceId)
// Return from cache if available
if (boolCache.containsKey(keyStr)) {
return boolCache[keyStr]!!
}
boolCache[keyStr]?.let { return it }
val default = defaultKey(keyResourceId, "bool").let {
if (it == 0) {
@@ -119,11 +111,7 @@ class Preferences(context: Context) {
fun getBoolean(@StringRes keyResourceId: Int, default: Boolean): Boolean {
val keyStr = key(keyResourceId)
// Return from cache if available
if (boolCache.containsKey(keyStr)) {
return boolCache[keyStr]!!
}
boolCache[keyStr]?.let { return it }
val value = preferences.getBoolean(keyStr, default)
boolCache[keyStr] = value
@@ -132,33 +120,30 @@ class Preferences(context: Context) {
fun putBoolean(@StringRes keyResourceId: Int, value: Boolean) {
val keyStr = key(keyResourceId)
val edit = preferences.edit()
edit.putBoolean(keyStr, value)
edit.apply()
// Update cache
preferences.edit().putBoolean(keyStr, value).apply()
boolCache[keyStr] = value
stringCache.remove(keyStr)
nullStringKeys.remove(keyStr)
intCache.remove(keyStr)
}
/**
* Clears the in-memory cache but NOT the SharedPreferences
* Call this when you know preferences have been updated externally
*/
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)
)
}
}
Binary file not shown.
+1 -1
View File
@@ -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