diff --git a/CHANGELOG.md b/CHANGELOG.md
index e2a53a4..ab9fb79 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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
diff --git a/PIPELINE_CHANGELOG.md b/PIPELINE_CHANGELOG.md
new file mode 100644
index 0000000..9749697
--- /dev/null
+++ b/PIPELINE_CHANGELOG.md
@@ -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)
diff --git a/README.md b/README.md
index dde7559..248dd64 100644
--- a/README.md
+++ b/README.md
@@ -1,25 +1,76 @@
-
# 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).
diff --git a/app/build.gradle b/app/build.gradle
index 95499e6..5f1fd6a 100755
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -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 {
diff --git a/app/src/main/java/com/hyperion/grabber/MainActivity.java b/app/src/main/java/com/hyperion/grabber/MainActivity.java
index f0856fb..330c6fe 100755
--- a/app/src/main/java/com/hyperion/grabber/MainActivity.java
+++ b/app/src/main/java/com/hyperion/grabber/MainActivity.java
@@ -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());
diff --git a/app/src/main/java/com/hyperion/grabber/tv/activities/MainActivity.java b/app/src/main/java/com/hyperion/grabber/tv/activities/MainActivity.java
index fecabbb..5987ab8 100644
--- a/app/src/main/java/com/hyperion/grabber/tv/activities/MainActivity.java
+++ b/app/src/main/java/com/hyperion/grabber/tv/activities/MainActivity.java
@@ -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)
diff --git a/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/BasicSettingsStepFragment.kt b/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/BasicSettingsStepFragment.kt
index 3704721..56bb200 100644
--- a/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/BasicSettingsStepFragment.kt
+++ b/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/BasicSettingsStepFragment.kt
@@ -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)
}
diff --git a/build.gradle b/build.gradle
index bb57199..1758317 100755
--- a/build.gradle
+++ b/build.gradle
@@ -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
diff --git a/common/src/main/java/com/hyperion/grabber/BootActivity.java b/common/src/main/java/com/hyperion/grabber/BootActivity.java
index 408f418..2b81671 100644
--- a/common/src/main/java/com/hyperion/grabber/BootActivity.java
+++ b/common/src/main/java/com/hyperion/grabber/BootActivity.java
@@ -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();
}
diff --git a/common/src/main/java/com/hyperion/grabber/HyperionScreenEncoder.java b/common/src/main/java/com/hyperion/grabber/HyperionScreenEncoder.java
index cc6d385..94fc43b 100644
--- a/common/src/main/java/com/hyperion/grabber/HyperionScreenEncoder.java
+++ b/common/src/main/java/com/hyperion/grabber/HyperionScreenEncoder.java
@@ -2,116 +2,153 @@ package com.hyperion.grabber.common;
import android.annotation.TargetApi;
import android.content.Context;
-import android.graphics.PixelFormat;
+import android.graphics.Rect;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
-import android.media.ImageReader;
import android.media.MediaCodec;
+import android.media.MediaCodecInfo;
+import android.media.MediaFormat;
import android.media.projection.MediaProjection;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
-import androidx.annotation.RequiresApi;
+import android.os.SystemClock;
import android.util.Log;
+import android.view.Surface;
+
+import androidx.annotation.RequiresApi;
import com.hyperion.grabber.common.network.HyperionThread;
-import com.hyperion.grabber.common.util.BorderProcessor;
-import com.hyperion.grabber.common.util.HyperionGrabberOptions;
import com.hyperion.grabber.common.util.AnimationSyncController;
-import com.hyperion.grabber.common.util.Preferences;
import com.hyperion.grabber.common.util.AudioVisualizerController;
+import com.hyperion.grabber.common.util.HyperionGrabberOptions;
+import com.hyperion.grabber.common.util.Preferences;
import java.nio.ByteBuffer;
+/**
+ * Screen capture via MediaProjection → VirtualDisplay → MediaCodec encoder Surface
+ * → MediaCodec decoder → YUV→RGB (scrcpy/recorder-like path).
+ *
+ * Avoids ImageReader as the MediaProjection consumer, which yields black frames on
+ * some Amlogic SoCs (e.g. S905X5M / Ugoos X5M Pro).
+ */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public final class HyperionScreenEncoder extends HyperionScreenEncoderBase {
private static final String TAG = "HyperionScreenEncoder";
- private static final boolean DEBUG = false;
-
- private static final int IMAGE_READER_IMAGES = 2;
- private static final int BORDER_CHECK_FRAMES = 60;
- private static final int BYTES_PER_PIXEL_RGBA = 4;
+ private static final boolean DEBUG = true;
+
+ private static final String MIME_TYPE = MediaFormat.MIMETYPE_VIDEO_AVC;
+ private static final int MAX_CAPTURE_WIDTH = 640;
+ private static final int MIN_CAPTURE_SIDE = 160;
+ private static final int MAX_OUTPUT_WIDTH = 128;
+ private static final int MAX_OUTPUT_HEIGHT = 72;
private static final int BYTES_PER_PIXEL_RGB = 3;
private static final int RGB_BUFFER_RING_SIZE = 3;
-
+ private static final int CODEC_TIMEOUT_US = 5_000;
+ private static final long FPS_LOG_INTERVAL_MS = 5_000L;
+ private static final int CONTENT_BOUNDS_LOCK_STABLE = 2;
+ private static final int CONTENT_BOUNDS_HYSTERESIS_PX = 16;
+ private static final int BLACK_Y_THRESHOLD = 32;
+ /** ~1.5 Mbps — enough for LED colors, light on Amlogic. */
+ private static final int MIN_ENCODER_BITRATE = 1_500_000;
+ private static final float LETTERBOX_FILL_MAX = 0.70f;
+
private VirtualDisplay mVirtualDisplay;
- private ImageReader mImageReader;
- private HandlerThread mCaptureThread;
- private Handler mCaptureHandler;
+ private MediaCodec mEncoder;
+ private MediaCodec mDecoder;
+ private Surface mEncoderSurface;
+ private HandlerThread mCodecThread;
+ private Handler mCodecHandler;
private volatile boolean mRunning;
+ private volatile boolean mDisplayPaused;
+ private volatile boolean mDecoderConfigured;
+
private int mCaptureWidth;
private int mCaptureHeight;
- private byte[] mRowBuffer;
- private final byte[] mAvgColorResult = new byte[3];
- private int mBorderX;
- private int mBorderY;
- private int mFrameCount;
-
+ private int mOutputWidth;
+ private int mOutputHeight;
+ private int mScreenWidth;
+ private int mScreenHeight;
+ private final Rect mContentBounds = new Rect();
+ private final Rect mPendingBounds = new Rect();
+ private boolean mContentBoundsValid;
+ private boolean mContentBoundsLocked;
+ private int mBoundsFrameCounter;
+ private int mStableBoundsCount;
+
private byte[][] mRgbBufferRing = new byte[RGB_BUFFER_RING_SIZE][];
private int mRgbBufferIndex = 0;
-
- private int mLastCachedBorderX = -1;
- private int mLastCachedBorderY = -1;
-
- private long mLastCaptureTimeNs = 0;
- private int mHighLoadCount = 0;
- private static final int HIGH_LOAD_THRESHOLD = 3;
- private static final double DEADLINE_MISS_RATIO = 0.85;
-
+ private final byte[] mAvgColorResult = new byte[3];
+
+ private final long mFrameIntervalMs;
+ private long mLastFrameSentAtMs;
+ private long mFpsWindowStartMs;
+ private int mFpsWindowCount;
+ private int mFramesSent;
+ private int mBlackFrameCount;
+
private AnimationSyncController mAnimationSync;
private Preferences mPreferences;
private AudioVisualizerController mAudioVisualizer;
private boolean mAudioOnlyMode = false;
private boolean mAnimationAutoEnabled = false;
-
- private final Runnable mCaptureRunnable = new Runnable() {
+
+ private final MediaCodec.BufferInfo mEncoderInfo = new MediaCodec.BufferInfo();
+ private final MediaCodec.BufferInfo mDecoderInfo = new MediaCodec.BufferInfo();
+
+ private final Runnable mCodecPump = new Runnable() {
@Override
public void run() {
if (!mRunning) return;
-
- final long start = System.nanoTime();
- captureFrame();
-
- if (mRunning && mCaptureHandler != null) {
- final long elapsedMs = (System.nanoTime() - start) / 1_000_000L;
- long effectiveDelayMs = mFrameIntervalMs - elapsedMs;
-
- if (mAnimationSync != null) {
- effectiveDelayMs += mAnimationSync.getEffectiveFrameDelayNs() / 1_000_000L;
+ try {
+ if (mAudioOnlyMode && mAudioVisualizer != null) {
+ generateAudioVisualization();
+ } else {
+ // Keep draining even if VD reported pause — otherwise Home freezes LEDs
+ // permanently. feedDecoder must never busy-loop (that froze the box on resume).
+ drainEncoderFeedDecoder();
+ drainDecoderToRgb();
}
-
- final long delayMs = Math.max(1L, effectiveDelayMs);
- mCaptureHandler.postDelayed(this, delayMs);
+ } catch (Exception e) {
+ Log.e(TAG, "Codec pump error: " + e.getMessage(), e);
+ }
+ if (mRunning && mCodecHandler != null) {
+ // Never spin at 1ms — that froze the X5M. Pace to target FPS.
+ mCodecHandler.postDelayed(this, Math.max(8L, mFrameIntervalMs));
}
}
};
-
- private final long mFrameIntervalMs;
-
+
private final VirtualDisplay.Callback mDisplayCallback = new VirtualDisplay.Callback() {
@Override
public void onPaused() {
- if (DEBUG) Log.d(TAG, "Display paused");
+ mDisplayPaused = true;
+ Log.i(TAG, "VirtualDisplay paused (pump keeps running, no busy-wait)");
}
@Override
public void onResumed() {
- if (DEBUG) Log.d(TAG, "Display resumed");
- if (!mRunning) startCapture();
+ Log.i(TAG, "VirtualDisplay resumed");
+ mDisplayPaused = false;
+ if (!mRunning) {
+ startCapture();
+ } else if (mCodecHandler != null) {
+ mCodecHandler.removeCallbacks(mCodecPump);
+ mCodecHandler.post(mCodecPump);
+ }
}
@Override
public void onStopped() {
- if (DEBUG) Log.d(TAG, "Display stopped");
+ Log.i(TAG, "VirtualDisplay stopped");
mRunning = false;
+ mDisplayPaused = true;
setCapturing(false);
}
};
- /**
- * Creates a new screen encoder.
- */
HyperionScreenEncoder(HyperionThread.HyperionThreadListener listener,
MediaProjection projection,
int screenWidth, int screenHeight,
@@ -119,18 +156,16 @@ public final class HyperionScreenEncoder extends HyperionScreenEncoderBase {
HyperionGrabberOptions options,
Context context) {
super(listener, projection, screenWidth, screenHeight, density, options);
-
- mFrameIntervalMs = 1000L / mFrameRate;
- initCaptureDimensions();
-
+
+ mFrameIntervalMs = 1000L / Math.max(1, mFrameRate);
+ initDimensions(screenWidth, screenHeight);
+
if (context != null) {
mPreferences = new Preferences(context);
int frameDelay = mPreferences.getInt(R.string.pref_key_frame_delay, 0);
boolean enableAnimation = mPreferences.getBoolean(R.string.pref_key_enable_animation, false);
mAudioOnlyMode = mPreferences.getBoolean(R.string.pref_key_audio_only_mode, false);
-
mAnimationSync = new AnimationSyncController(frameDelay, enableAnimation);
-
if (mAudioOnlyMode) {
mAudioVisualizer = new AudioVisualizerController();
mAnimationAutoEnabled = true;
@@ -138,363 +173,649 @@ public final class HyperionScreenEncoder extends HyperionScreenEncoderBase {
} else {
mAnimationSync = new AnimationSyncController(0, false);
}
-
- if (DEBUG) Log.d(TAG, "Capture: " + mCaptureWidth + "x" + mCaptureHeight + " @ " + mFrameRate + "fps");
- if (mAudioOnlyMode) Log.d(TAG, "Audio-only visualization mode enabled");
-
+
+ Log.i(TAG, "Pipeline=MediaCodec capture=" + mCaptureWidth + "x" + mCaptureHeight
+ + " output=" + mOutputWidth + "x" + mOutputHeight
+ + " fps=" + mFrameRate + " density=" + density);
+
try {
init();
- } catch (MediaCodec.CodecException e) {
- Log.e(TAG, "Init failed", e);
+ } catch (Exception e) {
+ Log.e(TAG, "MediaCodec pipeline init failed", e);
+ releaseCodecResources();
}
}
-
- private void initCaptureDimensions() {
- int w = Math.max(4, Math.min(getGrabberWidth(), 128));
- int h = Math.max(4, Math.min(getGrabberHeight(), 72));
- mCaptureWidth = w & ~1;
- mCaptureHeight = h & ~1;
+
+ private void initDimensions(int screenWidth, int screenHeight) {
+ mScreenWidth = Math.max(1, screenWidth);
+ mScreenHeight = Math.max(1, screenHeight);
+
+ mOutputWidth = Math.max(4, Math.min(getGrabberWidth(), MAX_OUTPUT_WIDTH)) & ~1;
+ mOutputHeight = Math.max(4, Math.min(getGrabberHeight(), MAX_OUTPUT_HEIGHT)) & ~1;
+
+ // Keep capture small on Amlogic — 960x540 + encode/decode froze the box.
+ float aspect = (float) mScreenWidth / (float) mScreenHeight;
+ if (Math.abs(aspect - (16f / 9f)) < 0.05f) {
+ mCaptureWidth = 640;
+ mCaptureHeight = 360;
+ } else {
+ int capW = Math.min(MAX_CAPTURE_WIDTH, mScreenWidth) & ~1;
+ int capH = Math.round(capW / aspect) & ~1;
+ if (capH < MIN_CAPTURE_SIDE) {
+ capH = MIN_CAPTURE_SIDE & ~1;
+ capW = Math.round(capH * aspect) & ~1;
+ }
+ mCaptureWidth = Math.max(MIN_CAPTURE_SIDE, capW);
+ mCaptureHeight = Math.max(MIN_CAPTURE_SIDE, capH);
+ }
+
+ Log.i(TAG, "Screen=" + mScreenWidth + "x" + mScreenHeight
+ + " capture=" + mCaptureWidth + "x" + mCaptureHeight
+ + " output=" + mOutputWidth + "x" + mOutputHeight);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
- private void init() throws MediaCodec.CodecException {
- mCaptureThread = new HandlerThread(TAG, android.os.Process.THREAD_PRIORITY_BACKGROUND);
- mCaptureThread.start();
- mCaptureHandler = new Handler(mCaptureThread.getLooper());
+ private void init() throws Exception {
+ mCodecThread = new HandlerThread(TAG + "-codec", android.os.Process.THREAD_PRIORITY_BACKGROUND);
+ mCodecThread.start();
+ mCodecHandler = new Handler(mCodecThread.getLooper());
- mImageReader = ImageReader.newInstance(
- mCaptureWidth, mCaptureHeight,
- PixelFormat.RGBA_8888,
- IMAGE_READER_IMAGES);
+ setupEncoder();
+ setupDecoder();
mMediaProjection.registerCallback(new MediaProjection.Callback() {
@Override
public void onStop() {
+ Log.i(TAG, "MediaProjection stopped");
stopRecording();
}
}, mHandler);
+ int flags = DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR;
+ Log.i(TAG, "Creating VirtualDisplay flags=AUTO_MIRROR surface=MediaCodecEncoder");
mVirtualDisplay = mMediaProjection.createVirtualDisplay(
TAG,
mCaptureWidth, mCaptureHeight, mDensity,
- DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC,
- mImageReader.getSurface(),
+ flags,
+ mEncoderSurface,
mDisplayCallback,
mHandler);
+ if (mVirtualDisplay == null) {
+ throw new IllegalStateException("createVirtualDisplay returned null");
+ }
+ Log.i(TAG, "VirtualDisplay created OK");
+
startCapture();
}
+ private void setupEncoder() throws Exception {
+ MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mCaptureWidth, mCaptureHeight);
+ format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
+ MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
+ // Low-ish bitrate: LED ambilight does not need cinema quality; high bitrate froze X5M.
+ final int bitrate = Math.max(MIN_ENCODER_BITRATE, mCaptureWidth * mCaptureHeight * 3);
+ format.setInteger(MediaFormat.KEY_BIT_RATE, bitrate);
+ format.setInteger(MediaFormat.KEY_FRAME_RATE, Math.min(30, Math.max(10, mFrameRate)));
+ format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2);
+ format.setInteger(MediaFormat.KEY_BITRATE_MODE,
+ MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR);
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ format.setInteger(MediaFormat.KEY_LATENCY, 0);
+ }
+
+ Log.i(TAG, "Encoder format bitrate=" + bitrate + " : " + format);
+ mEncoder = MediaCodec.createEncoderByType(MIME_TYPE);
+ mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
+ mEncoderSurface = mEncoder.createInputSurface();
+ mEncoder.start();
+ Log.i(TAG, "Encoder started: " + mEncoder.getName());
+ }
+
+ private void setupDecoder() throws Exception {
+ MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mCaptureWidth, mCaptureHeight);
+ // ByteBuffer / Image mode — not ImageReader as MediaProjection consumer.
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
+ MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible);
+ }
+ Log.i(TAG, "Decoder format: " + format);
+ mDecoder = MediaCodec.createDecoderByType(MIME_TYPE);
+ mDecoder.configure(format, null, null, 0);
+ mDecoder.start();
+ mDecoderConfigured = true;
+ Log.i(TAG, "Decoder started: " + mDecoder.getName());
+ }
+
private void startCapture() {
mRunning = true;
+ mDisplayPaused = false;
setCapturing(true);
- mFrameCount = 0;
-
+ mFpsWindowStartMs = SystemClock.elapsedRealtime();
+ mFpsWindowCount = 0;
+ mFramesSent = 0;
+ mBlackFrameCount = 0;
+ mLastFrameSentAtMs = 0;
+ // Keep letterbox lock across pause/resume — only reset on fresh pipeline init.
+ if (!mContentBoundsLocked) {
+ mContentBoundsValid = false;
+ mBoundsFrameCounter = 0;
+ mStableBoundsCount = 0;
+ }
+
if (mAudioOnlyMode && mAudioVisualizer != null) {
mAudioVisualizer.start();
if (mAnimationSync != null && mAnimationAutoEnabled) {
mAnimationSync.setAnimationEnabled(true);
}
}
-
- mCaptureHandler.post(mCaptureRunnable);
+
+ if (mCodecHandler != null) {
+ mCodecHandler.removeCallbacks(mCodecPump);
+ mCodecHandler.post(mCodecPump);
+ }
+ Log.i(TAG, "Capture started (MediaCodec path)");
}
-
- private void captureFrame() {
- long frameStart = System.nanoTime();
-
- if (mAudioOnlyMode && mAudioVisualizer != null) {
- generateAudioVisualization();
- long captureTime = System.nanoTime() - frameStart;
- mLastCaptureTimeNs = captureTime;
- updateLoadTracking(captureTime);
+
+ private void drainEncoderFeedDecoder() {
+ if (mEncoder == null || mDecoder == null || !mDecoderConfigured) return;
+
+ // Cap work per tick so a backlog cannot freeze the box.
+ final int maxPackets = 8;
+ for (int n = 0; n < maxPackets; n++) {
+ int outIndex = mEncoder.dequeueOutputBuffer(mEncoderInfo, 0);
+ if (outIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
+ break;
+ } else if (outIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
+ Log.i(TAG, "Encoder output format changed: " + mEncoder.getOutputFormat());
+ } else if (outIndex >= 0) {
+ ByteBuffer encoded = mEncoder.getOutputBuffer(outIndex);
+ boolean fed = false;
+ if (encoded != null && mEncoderInfo.size > 0) {
+ encoded.position(mEncoderInfo.offset);
+ encoded.limit(mEncoderInfo.offset + mEncoderInfo.size);
+ fed = feedDecoder(encoded, mEncoderInfo.size, mEncoderInfo.presentationTimeUs,
+ mEncoderInfo.flags);
+ }
+ // Always release — never hold encoder buffers while spinning on decoder.
+ mEncoder.releaseOutputBuffer(outIndex, false);
+ if (!fed && mEncoderInfo.size > 0) {
+ // Decoder was busy; free some output then continue next tick.
+ drainDecoderToRgb();
+ break;
+ }
+ if ((mEncoderInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+ }
+
+ /**
+ * @return true if the packet was queued; false if dropped (never busy-loops).
+ */
+ private boolean feedDecoder(ByteBuffer data, int size, long ptsUs, int flags) {
+ // Free decoder outputs first so input buffers become available.
+ drainDecoderToRgb();
+
+ for (int attempt = 0; attempt < 3; attempt++) {
+ if (!mRunning) return false;
+ int inIndex = mDecoder.dequeueInputBuffer(0);
+ if (inIndex >= 0) {
+ ByteBuffer input = mDecoder.getInputBuffer(inIndex);
+ if (input == null) return false;
+ input.clear();
+ if (size > input.capacity()) {
+ Log.w(TAG, "Encoded packet larger than decoder input, dropping");
+ return false;
+ }
+ input.put(data);
+ mDecoder.queueInputBuffer(inIndex, 0, size, ptsUs, flags);
+ return true;
+ }
+ if (inIndex != MediaCodec.INFO_TRY_AGAIN_LATER) {
+ return false;
+ }
+ drainDecoderToRgb();
+ }
+ return false;
+ }
+
+ private void drainDecoderToRgb() {
+ if (mDecoder == null) return;
+
+ long now = SystemClock.elapsedRealtime();
+ boolean throttle = (now - mLastFrameSentAtMs) < mFrameIntervalMs;
+ final int maxFrames = 4;
+
+ for (int n = 0; n < maxFrames; n++) {
+ int outIndex = mDecoder.dequeueOutputBuffer(mDecoderInfo, 0);
+ if (outIndex == MediaCodec.INFO_TRY_AGAIN_LATER) {
+ break;
+ } else if (outIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
+ Log.i(TAG, "Decoder output format: " + mDecoder.getOutputFormat());
+ } else if (outIndex >= 0) {
+ boolean render = mDecoderInfo.size > 0 && !throttle;
+ if (render) {
+ Image image = null;
+ try {
+ image = mDecoder.getOutputImage(outIndex);
+ if (image != null) {
+ processDecodedImage(image);
+ mLastFrameSentAtMs = now;
+ throttle = true;
+ }
+ } catch (Exception e) {
+ Log.w(TAG, "getOutputImage failed: " + e.getMessage());
+ } finally {
+ if (image != null) {
+ image.close();
+ }
+ }
+ }
+ mDecoder.releaseOutputBuffer(outIndex, false);
+
+ if ((mDecoderInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+ }
+
+ private void processDecodedImage(Image image) {
+ final int outW = mOutputWidth;
+ final int outH = mOutputHeight;
+ byte[] rgb = getRgbBuffer(outW, outH);
+
+ if (mAvgColor) {
+ computeAverageColor(image, rgb);
+ mListener.sendFrame(mAvgColorResult, 1, 1);
+ } else {
+ yuvToRgbDownscale(image, rgb, outW, outH);
+ if (mAnimationSync != null) {
+ rgb = mAnimationSync.applyAnimationToFrame(rgb);
+ }
+ logFrameStats(rgb, outW, outH);
+ mListener.sendFrame(rgb, outW, outH);
+ }
+
+ mRgbBufferIndex = (mRgbBufferIndex + 1) % RGB_BUFFER_RING_SIZE;
+ mFramesSent++;
+ mFpsWindowCount++;
+ maybeLogFps();
+ }
+
+ private void logFrameStats(byte[] rgb, int width, int height) {
+ int sample = Math.min(rgb.length, 300);
+ int nonZero = 0;
+ long sum = 0;
+ for (int i = 0; i < sample; i++) {
+ int v = rgb[i] & 0xFF;
+ sum += v;
+ if (v != 0) nonZero++;
+ }
+ boolean black = nonZero == 0;
+ if (black) {
+ mBlackFrameCount++;
+ }
+ if (DEBUG && (mFramesSent < 5 || mFramesSent % 60 == 0 || black)) {
+ Log.i(TAG, "Frame#" + mFramesSent + " " + width + "x" + height
+ + " nonZeroSample=" + nonZero + "/" + sample
+ + " avgSample=" + (sample > 0 ? (sum / sample) : 0)
+ + " blackFrames=" + mBlackFrameCount);
+ }
+ }
+
+ private void maybeLogFps() {
+ long now = SystemClock.elapsedRealtime();
+ long elapsed = now - mFpsWindowStartMs;
+ if (elapsed >= FPS_LOG_INTERVAL_MS) {
+ float fps = mFpsWindowCount * 1000f / elapsed;
+ Log.i(TAG, "Send-FPS=" + String.format("%.1f", fps)
+ + " framesSent=" + mFramesSent
+ + " blackFrames=" + mBlackFrameCount
+ + " capture=" + mCaptureWidth + "x" + mCaptureHeight
+ + " output=" + mOutputWidth + "x" + mOutputHeight);
+ mFpsWindowStartMs = now;
+ mFpsWindowCount = 0;
+ }
+ }
+
+ private void yuvToRgbDownscale(Image image, byte[] rgb, int outW, int outH) {
+ final Image.Plane[] planes = image.getPlanes();
+ if (planes.length < 3) {
+ Log.w(TAG, "Unexpected plane count: " + planes.length);
return;
}
-
- Image img = null;
- try {
- img = mImageReader.acquireLatestImage();
- if (img != null) {
- boolean skipBorderDetection = mHighLoadCount > 0;
- boolean skipAverageColor = mHighLoadCount > HIGH_LOAD_THRESHOLD;
- processImage(img, skipBorderDetection, skipAverageColor);
- }
- } catch (IllegalStateException e) {
- if (DEBUG) Log.w(TAG, "ImageReader is closed, stopping capture");
- mRunning = false;
- } catch (Exception e) {
- if (DEBUG) Log.w(TAG, "Capture error: " + e.getMessage(), e);
- } finally {
- if (img != null) {
- try {
- img.close();
- } catch (Exception e) {
- Log.w(TAG, "Failed to close image: " + e.getMessage());
- }
- }
- long captureTime = System.nanoTime() - frameStart;
- mLastCaptureTimeNs = captureTime;
- updateLoadTracking(captureTime);
- }
- }
-
- private void generateAudioVisualization() {
- if (mAudioVisualizer == null) return;
-
- int[] spectrum = mAudioVisualizer.getFullSpectrum();
- int[] visualization = AudioVisualizerController.generateAudioVisualization(
- mCaptureWidth, mCaptureHeight, spectrum);
-
- byte[] rgb = getRgbBuffer(mCaptureWidth, mCaptureHeight);
-
- for (int i = 0; i < visualization.length && i < rgb.length; i++) {
- rgb[i] = (byte) (visualization[i] & 0xFF);
- }
-
- if (mAnimationSync != null) {
- rgb = mAnimationSync.applyAnimationToFrame(rgb);
- }
-
- mListener.sendFrame(rgb, mCaptureWidth, mCaptureHeight);
- mRgbBufferIndex = (mRgbBufferIndex + 1) % RGB_BUFFER_RING_SIZE;
- }
- private void updateLoadTracking(long captureTimeNs) {
- if (captureTimeNs > (long)(mFrameIntervalMs * 1_000_000 * DEADLINE_MISS_RATIO)) {
- mHighLoadCount = Math.min(5, mHighLoadCount + 1);
- } else {
- mHighLoadCount = Math.max(0, mHighLoadCount - 1);
+ final ByteBuffer yBuf = planes[0].getBuffer();
+ final ByteBuffer uBuf = planes[1].getBuffer();
+ final ByteBuffer vBuf = planes[2].getBuffer();
+ final int yRowStride = planes[0].getRowStride();
+ final int yPixelStride = planes[0].getPixelStride();
+ final int uRowStride = planes[1].getRowStride();
+ final int uPixelStride = planes[1].getPixelStride();
+ final int vRowStride = planes[2].getRowStride();
+ final int vPixelStride = planes[2].getPixelStride();
+
+ // Decoder crop (coded buffer may be larger than the active picture).
+ final Rect crop = new Rect(image.getCropRect());
+ if (crop.isEmpty()) {
+ crop.set(0, 0, image.getWidth(), image.getHeight());
+ }
+
+ // Amlogic letterboxes the real picture into part of the encoder frame.
+ // Scan every frame until locked; then keep the crop fixed (no jitter).
+ if (!mContentBoundsLocked) {
+ updateContentBounds(yBuf, yRowStride, yPixelStride, crop);
+ }
+ if (!mContentBoundsValid) {
+ mContentBounds.set(crop);
+ mContentBoundsValid = true;
+ }
+
+ final int srcLeft = mContentBounds.left;
+ final int srcTop = mContentBounds.top;
+ final int srcW = Math.max(2, mContentBounds.width());
+ final int srcH = Math.max(2, mContentBounds.height());
+
+ if (DEBUG && mFramesSent < 5) {
+ Log.i(TAG, "YUV image=" + image.getWidth() + "x" + image.getHeight()
+ + " crop=" + crop.toShortString()
+ + " content=" + mContentBounds.toShortString()
+ + " yStride=" + yRowStride);
+ }
+
+ int idx = 0;
+ for (int oy = 0; oy < outH; oy++) {
+ final int iy = srcTop + oy * srcH / outH;
+ final int uvRow = iy >> 1;
+ for (int ox = 0; ox < outW; ox++) {
+ final int ix = srcLeft + ox * srcW / outW;
+ final int y = yBuf.get(iy * yRowStride + ix * yPixelStride) & 0xFF;
+ final int uvCol = ix >> 1;
+ final int u = (uBuf.get(uvRow * uRowStride + uvCol * uPixelStride) & 0xFF) - 128;
+ final int v = (vBuf.get(uvRow * vRowStride + uvCol * vPixelStride) & 0xFF) - 128;
+
+ int r = y + ((359 * v) >> 8);
+ int g = y - ((88 * u + 183 * v) >> 8);
+ int b = y + ((454 * u) >> 8);
+
+ rgb[idx++] = (byte) clamp(r);
+ rgb[idx++] = (byte) clamp(g);
+ rgb[idx++] = (byte) clamp(b);
+ }
}
}
- private void processImage(Image img, boolean skipBorderDetection, boolean skipAverageColor) {
- final Image.Plane[] planes = img.getPlanes();
- if (planes.length == 0) return;
-
- final Image.Plane plane = planes[0];
- final ByteBuffer buffer = plane.getBuffer();
- final int width = img.getWidth();
- final int height = img.getHeight();
- final int pixelStride = plane.getPixelStride();
- final int rowStride = plane.getRowStride();
-
- if (!skipBorderDetection) {
- updateBorderDetection(buffer, width, height, rowStride, pixelStride);
+ /**
+ * Detects letterboxed active picture by scanning inward from each edge until a row/column
+ * has enough bright pixels. More robust than a min/max bbox (noise in black bars expands that).
+ */
+ private void updateContentBounds(ByteBuffer yBuf, int yRowStride, int yPixelStride, Rect crop) {
+ final Rect detected = detectLetterboxByEdges(yBuf, yRowStride, yPixelStride, crop);
+ final float fill = (detected.width() * (float) detected.height())
+ / Math.max(1, crop.width() * crop.height());
+
+ // Amlogic consistently letterboxes into a stable top-left region — lock ASAP.
+ if (fill > 0.05f && fill <= LETTERBOX_FILL_MAX) {
+ mContentBounds.set(detected);
+ mContentBoundsValid = true;
+ mContentBoundsLocked = true;
+ Log.i(TAG, "Content bounds LOCKED " + detected.toShortString()
+ + " fill=" + String.format("%.0f%%", fill * 100f)
+ + " of " + crop.width() + "x" + crop.height());
+ return;
}
-
- if (mAvgColor && !skipAverageColor) {
- sendAverageColor(buffer, width, height, rowStride, pixelStride);
+
+ if (!mContentBoundsValid) {
+ mContentBounds.set(crop);
+ mPendingBounds.set(detected);
+ mContentBoundsValid = true;
+ mStableBoundsCount = 1;
+ Log.i(TAG, "Content bounds fallback full-frame fill="
+ + String.format("%.0f%%", fill * 100f));
+ return;
+ }
+
+ if (boundsSimilar(mPendingBounds, detected, CONTENT_BOUNDS_HYSTERESIS_PX)) {
+ mStableBoundsCount++;
+ if (mStableBoundsCount >= CONTENT_BOUNDS_LOCK_STABLE) {
+ mContentBounds.set(detected);
+ mContentBoundsLocked = true;
+ Log.i(TAG, "Content bounds LOCKED (stable) " + mContentBounds.toShortString());
+ }
} else {
- sendPixelData(buffer, width, height, rowStride, pixelStride);
+ mPendingBounds.set(detected);
+ mStableBoundsCount = 1;
}
}
-
- private void updateBorderDetection(ByteBuffer buffer, int width, int height,
- int rowStride, int pixelStride) {
- if (!mRemoveBorders && !mAvgColor) return;
-
- if (++mFrameCount >= BORDER_CHECK_FRAMES) {
- mFrameCount = 0;
- mBorderProcessor.parseBorder(buffer, width, height, rowStride, pixelStride);
- final BorderProcessor.BorderObject border = mBorderProcessor.getCurrentBorder();
- if (border != null && border.isKnown()) {
- int newBorderX = border.getHorizontalBorderIndex();
- int newBorderY = border.getVerticalBorderIndex();
- if (newBorderX != mLastCachedBorderX || newBorderY != mLastCachedBorderY) {
- mBorderX = newBorderX;
- mBorderY = newBorderY;
- mLastCachedBorderX = newBorderX;
- mLastCachedBorderY = newBorderY;
- }
+
+ private Rect detectLetterboxByEdges(ByteBuffer yBuf, int yRowStride, int yPixelStride, Rect crop) {
+ final int threshold = BLACK_Y_THRESHOLD;
+ final int minBright = Math.max(3, Math.min(crop.width(), crop.height()) / 64);
+ // Coarse scan — cheap; only runs until lock.
+ final int step = 8;
+
+ int top = crop.top;
+ for (; top < crop.bottom - 2; top += step) {
+ if (countBrightInRow(yBuf, yRowStride, yPixelStride, crop.left, crop.right, top, threshold)
+ >= minBright) {
+ break;
}
}
- }
-
- private void sendPixelData(ByteBuffer buffer, int width, int height,
- int rowStride, int pixelStride) {
- final int bx = mBorderX;
- final int by = mBorderY;
- final int effWidth = width - (bx << 1);
- final int effHeight = height - (by << 1);
-
- if (effWidth <= 0 || effHeight <= 0) return;
-
- byte[] rgb = getRgbBuffer(effWidth, effHeight);
- extractRgb(buffer, width, height, rowStride, pixelStride, bx, by, effWidth, effHeight, rgb);
-
- if (mAnimationSync != null) {
- rgb = mAnimationSync.applyAnimationToFrame(rgb);
- }
-
- mListener.sendFrame(rgb, effWidth, effHeight);
-
- mRgbBufferIndex = (mRgbBufferIndex + 1) % RGB_BUFFER_RING_SIZE;
- }
-
- private byte[] getRgbBuffer(int effWidth, int effHeight) {
- int requiredSize = effWidth * effHeight * BYTES_PER_PIXEL_RGB;
- byte[] buffer = mRgbBufferRing[mRgbBufferIndex];
-
- if (buffer == null || buffer.length < requiredSize) {
- buffer = new byte[requiredSize];
- mRgbBufferRing[mRgbBufferIndex] = buffer;
- }
-
- return buffer;
- }
-
- private void extractRgb(ByteBuffer buffer, int width, int height,
- int rowStride, int pixelStride,
- int bx, int by, int effWidth, int effHeight, byte[] rgb) {
- final int endY = height - by;
- final int endX = width - bx;
- int rgbIdx = 0;
-
- if (pixelStride == BYTES_PER_PIXEL_RGBA && rowStride == width * BYTES_PER_PIXEL_RGBA) {
- final int rowBytes = effWidth * BYTES_PER_PIXEL_RGBA;
-
- if (mRowBuffer == null || mRowBuffer.length < rowBytes) {
- mRowBuffer = new byte[rowBytes];
- }
-
- final int savedPos = buffer.position();
-
- for (int y = by; y < endY; y++) {
- buffer.position(y * rowStride + bx * BYTES_PER_PIXEL_RGBA);
- buffer.get(mRowBuffer, 0, rowBytes);
-
- int i = 0;
- final int unrollLimit = rowBytes - 15;
- for (; i < unrollLimit; i += 16) {
- rgb[rgbIdx++] = mRowBuffer[i];
- rgb[rgbIdx++] = mRowBuffer[i + 1];
- rgb[rgbIdx++] = mRowBuffer[i + 2];
- rgb[rgbIdx++] = mRowBuffer[i + 4];
- rgb[rgbIdx++] = mRowBuffer[i + 5];
- rgb[rgbIdx++] = mRowBuffer[i + 6];
- rgb[rgbIdx++] = mRowBuffer[i + 8];
- rgb[rgbIdx++] = mRowBuffer[i + 9];
- rgb[rgbIdx++] = mRowBuffer[i + 10];
- rgb[rgbIdx++] = mRowBuffer[i + 12];
- rgb[rgbIdx++] = mRowBuffer[i + 13];
- rgb[rgbIdx++] = mRowBuffer[i + 14];
- }
- for (; i < rowBytes; i += BYTES_PER_PIXEL_RGBA) {
- rgb[rgbIdx++] = mRowBuffer[i];
- rgb[rgbIdx++] = mRowBuffer[i + 1];
- rgb[rgbIdx++] = mRowBuffer[i + 2];
- }
- }
-
- buffer.position(savedPos);
- } else {
- for (int y = by; y < endY; y++) {
- final int rowOff = y * rowStride;
- for (int x = bx; x < endX; x++) {
- final int off = rowOff + x * pixelStride;
- rgb[rgbIdx++] = buffer.get(off);
- rgb[rgbIdx++] = buffer.get(off + 1);
- rgb[rgbIdx++] = buffer.get(off + 2);
- }
+
+ int bottom = crop.bottom - 1;
+ for (; bottom > top + 2; bottom -= step) {
+ if (countBrightInRow(yBuf, yRowStride, yPixelStride, crop.left, crop.right, bottom, threshold)
+ >= minBright) {
+ break;
}
}
+
+ int left = crop.left;
+ for (; left < crop.right - 2; left += step) {
+ if (countBrightInCol(yBuf, yRowStride, yPixelStride, left, top, bottom, threshold)
+ >= minBright) {
+ break;
+ }
+ }
+
+ int right = crop.right - 1;
+ for (; right > left + 2; right -= step) {
+ if (countBrightInCol(yBuf, yRowStride, yPixelStride, right, top, bottom, threshold)
+ >= minBright) {
+ break;
+ }
+ }
+
+ if (right - left < 8 || bottom - top < 8) {
+ return new Rect(crop);
+ }
+
+ left = Math.max(crop.left, left) & ~1;
+ top = Math.max(crop.top, top) & ~1;
+ right = Math.min(crop.right, right + 1);
+ bottom = Math.min(crop.bottom, bottom + 1);
+ if (((right - left) & 1) != 0) right = Math.min(crop.right, right + 1);
+ if (((bottom - top) & 1) != 0) bottom = Math.min(crop.bottom, bottom + 1);
+
+ return new Rect(left, top, right, bottom);
}
-
- private void sendAverageColor(ByteBuffer buffer, int width, int height,
- int rowStride, int pixelStride) {
- final int bx = mBorderX;
- final int by = mBorderY;
- final int startX = bx;
- final int startY = by;
- final int endX = width - bx;
- final int endY = height - by;
-
- if (endX <= startX || endY <= startY) return;
-
- long r = 0, g = 0, b = 0;
+
+ private static int countBrightInRow(ByteBuffer yBuf, int yRowStride, int yPixelStride,
+ int x0, int x1, int y, int threshold) {
int count = 0;
-
- for (int y = startY; y < endY; y += 4) {
- final int rowOff = y * rowStride;
- for (int x = startX; x < endX; x += 4) {
- final int off = rowOff + x * pixelStride;
- r += buffer.get(off) & 0xFF;
- g += buffer.get(off + 1) & 0xFF;
- b += buffer.get(off + 2) & 0xFF;
+ final int row = y * yRowStride;
+ for (int x = x0; x < x1; x += 4) {
+ if ((yBuf.get(row + x * yPixelStride) & 0xFF) > threshold) {
count++;
}
}
-
+ return count;
+ }
+
+ private static int countBrightInCol(ByteBuffer yBuf, int yRowStride, int yPixelStride,
+ int x, int y0, int y1, int threshold) {
+ int count = 0;
+ final int xOff = x * yPixelStride;
+ for (int y = y0; y <= y1; y += 4) {
+ if ((yBuf.get(y * yRowStride + xOff) & 0xFF) > threshold) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ private static boolean boundsSimilar(Rect a, Rect b, int tolerancePx) {
+ return Math.abs(a.left - b.left) <= tolerancePx
+ && Math.abs(a.top - b.top) <= tolerancePx
+ && Math.abs(a.right - b.right) <= tolerancePx
+ && Math.abs(a.bottom - b.bottom) <= tolerancePx;
+ }
+
+ private void computeAverageColor(Image image, byte[] scratch) {
+ yuvToRgbDownscale(image, scratch, mOutputWidth, mOutputHeight);
+ long r = 0, g = 0, b = 0;
+ int count = 0;
+ for (int i = 0; i + 2 < scratch.length; i += 3) {
+ r += scratch[i] & 0xFF;
+ g += scratch[i + 1] & 0xFF;
+ b += scratch[i + 2] & 0xFF;
+ count++;
+ }
if (count > 0) {
mAvgColorResult[0] = (byte) (r / count);
mAvgColorResult[1] = (byte) (g / count);
mAvgColorResult[2] = (byte) (b / count);
- mListener.sendFrame(mAvgColorResult, 1, 1);
}
}
+ private static int clamp(int value) {
+ if (value < 0) return 0;
+ if (value > 255) return 255;
+ return value;
+ }
+
+ private void generateAudioVisualization() {
+ if (mAudioVisualizer == null) return;
+
+ int[] spectrum = mAudioVisualizer.getFullSpectrum();
+ int[] visualization = AudioVisualizerController.generateAudioVisualization(
+ mOutputWidth, mOutputHeight, spectrum);
+
+ byte[] rgb = getRgbBuffer(mOutputWidth, mOutputHeight);
+ for (int i = 0; i < visualization.length && i < rgb.length; i++) {
+ rgb[i] = (byte) (visualization[i] & 0xFF);
+ }
+ if (mAnimationSync != null) {
+ rgb = mAnimationSync.applyAnimationToFrame(rgb);
+ }
+ mListener.sendFrame(rgb, mOutputWidth, mOutputHeight);
+ mRgbBufferIndex = (mRgbBufferIndex + 1) % RGB_BUFFER_RING_SIZE;
+ mFramesSent++;
+ mFpsWindowCount++;
+ maybeLogFps();
+ }
+
+ private byte[] getRgbBuffer(int width, int height) {
+ int requiredSize = width * height * BYTES_PER_PIXEL_RGB;
+ byte[] buffer = mRgbBufferRing[mRgbBufferIndex];
+ if (buffer == null || buffer.length < requiredSize) {
+ buffer = new byte[requiredSize];
+ mRgbBufferRing[mRgbBufferIndex] = buffer;
+ }
+ return buffer;
+ }
+
+ private void releaseCodecResources() {
+ if (mVirtualDisplay != null) {
+ try {
+ mVirtualDisplay.release();
+ } catch (Exception ignored) {}
+ mVirtualDisplay = null;
+ }
+ if (mEncoderSurface != null) {
+ try {
+ mEncoderSurface.release();
+ } catch (Exception ignored) {}
+ mEncoderSurface = null;
+ }
+ if (mEncoder != null) {
+ try {
+ mEncoder.stop();
+ } catch (Exception ignored) {}
+ try {
+ mEncoder.release();
+ } catch (Exception ignored) {}
+ mEncoder = null;
+ }
+ if (mDecoder != null) {
+ try {
+ mDecoder.stop();
+ } catch (Exception ignored) {}
+ try {
+ mDecoder.release();
+ } catch (Exception ignored) {}
+ mDecoder = null;
+ }
+ mDecoderConfigured = false;
+ }
+
@Override
public void stopRecording() {
- if (DEBUG) Log.i(TAG, "Stopping");
+ Log.i(TAG, "Stopping MediaCodec capture");
mRunning = false;
setCapturing(false);
-
+
if (mAudioVisualizer != null) {
mAudioVisualizer.stop();
mAudioVisualizer.release();
mAudioVisualizer = null;
}
-
- if (mCaptureHandler != null) {
- mCaptureHandler.removeCallbacksAndMessages(null);
+
+ if (mCodecHandler != null) {
+ mCodecHandler.removeCallbacksAndMessages(null);
}
-
- if (mVirtualDisplay != null) {
- mVirtualDisplay.release();
- mVirtualDisplay = null;
+
+ releaseCodecResources();
+
+ if (mCodecThread != null) {
+ mCodecThread.quitSafely();
+ mCodecThread = null;
+ mCodecHandler = null;
}
-
- if (mCaptureThread != null) {
- mCaptureThread.quitSafely();
- mCaptureThread = null;
- mCaptureHandler = null;
- }
-
+
mRgbBufferRing = new byte[RGB_BUFFER_RING_SIZE][];
mRgbBufferIndex = 0;
- mRowBuffer = null;
- mBorderX = 0;
- mBorderY = 0;
- mFrameCount = 0;
mAnimationSync = null;
mPreferences = null;
-
+
mHandler.getLooper().quit();
clearAndDisconnect();
-
- if (mImageReader != null) {
- mImageReader.close();
- mImageReader = null;
- }
}
@Override
public void pauseRecording() {
- if (DEBUG) Log.i(TAG, "Pausing");
+ Log.i(TAG, "Pausing");
mRunning = false;
setCapturing(false);
if (mAudioVisualizer != null) {
mAudioVisualizer.stop();
}
- if (mCaptureHandler != null) {
- mCaptureHandler.removeCallbacksAndMessages(null);
+ if (mCodecHandler != null) {
+ mCodecHandler.removeCallbacksAndMessages(null);
}
}
@Override
public void resumeRecording() {
- if (DEBUG) Log.i(TAG, "Resuming");
- if (!isCapturing() && mImageReader != null) {
+ Log.i(TAG, "Resuming");
+ if (!isCapturing() && mEncoderSurface != null) {
startCapture();
}
}
@@ -503,37 +824,60 @@ public final class HyperionScreenEncoder extends HyperionScreenEncoderBase {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void setOrientation(int orientation) {
if (mVirtualDisplay == null || orientation == mCurrentOrientation) return;
-
+
+ Log.i(TAG, "Orientation change — restarting MediaCodec pipeline");
mCurrentOrientation = orientation;
mRunning = false;
setCapturing(false);
-
- final int tmp = mCaptureWidth;
+
+ if (mCodecHandler != null) {
+ mCodecHandler.removeCallbacksAndMessages(null);
+ }
+
+ // Swap output dimensions; rebuild codecs at new capture size.
+ int tmp = mOutputWidth;
+ mOutputWidth = mOutputHeight;
+ mOutputHeight = tmp;
+
+ int tmpCap = mCaptureWidth;
mCaptureWidth = mCaptureHeight;
- mCaptureHeight = tmp;
-
- if (mCaptureHandler != null) {
- mCaptureHandler.removeCallbacksAndMessages(null);
+ mCaptureHeight = tmpCap;
+
+ try {
+ if (mVirtualDisplay != null) {
+ mVirtualDisplay.release();
+ mVirtualDisplay = null;
+ }
+ if (mEncoderSurface != null) {
+ mEncoderSurface.release();
+ mEncoderSurface = null;
+ }
+ if (mEncoder != null) {
+ mEncoder.stop();
+ mEncoder.release();
+ mEncoder = null;
+ }
+ if (mDecoder != null) {
+ mDecoder.stop();
+ mDecoder.release();
+ mDecoder = null;
+ }
+
+ setupEncoder();
+ setupDecoder();
+ mVirtualDisplay = mMediaProjection.createVirtualDisplay(
+ TAG,
+ mCaptureWidth, mCaptureHeight, mDensity,
+ DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
+ mEncoderSurface,
+ mDisplayCallback,
+ mHandler);
+ mRgbBufferRing = new byte[RGB_BUFFER_RING_SIZE][];
+ mRgbBufferIndex = 0;
+ startCapture();
+ } catch (Exception e) {
+ Log.e(TAG, "Orientation restart failed", e);
}
-
- mVirtualDisplay.resize(mCaptureWidth, mCaptureHeight, mDensity);
-
- if (mImageReader != null) {
- mImageReader.close();
- }
-
- mImageReader = ImageReader.newInstance(
- mCaptureWidth, mCaptureHeight,
- PixelFormat.RGBA_8888,
- IMAGE_READER_IMAGES);
-
- mVirtualDisplay.setSurface(mImageReader.getSurface());
-
- mRgbBufferRing = new byte[RGB_BUFFER_RING_SIZE][];
- mRgbBufferIndex = 0;
- mRowBuffer = null;
-
- startCapture();
}
@Override
diff --git a/common/src/main/java/com/hyperion/grabber/HyperionScreenService.java b/common/src/main/java/com/hyperion/grabber/HyperionScreenService.java
index 97c7ec3..955331a 100644
--- a/common/src/main/java/com/hyperion/grabber/HyperionScreenService.java
+++ b/common/src/main/java/com/hyperion/grabber/HyperionScreenService.java
@@ -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,
diff --git a/common/src/main/java/com/hyperion/grabber/ToggleActivity.java b/common/src/main/java/com/hyperion/grabber/ToggleActivity.java
index 0b86898..eb42e82 100644
--- a/common/src/main/java/com/hyperion/grabber/ToggleActivity.java
+++ b/common/src/main/java/com/hyperion/grabber/ToggleActivity.java
@@ -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);
diff --git a/common/src/main/java/com/hyperion/grabber/network/HyperionThread.kt b/common/src/main/java/com/hyperion/grabber/network/HyperionThread.kt
index f16300f..70ce24d 100644
--- a/common/src/main/java/com/hyperion/grabber/network/HyperionThread.kt
+++ b/common/src/main/java/com/hyperion/grabber/network/HyperionThread.kt
@@ -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() }
diff --git a/common/src/main/java/com/hyperion/grabber/util/MediaProjectionHelper.java b/common/src/main/java/com/hyperion/grabber/util/MediaProjectionHelper.java
new file mode 100644
index 0000000..49cac88
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/util/MediaProjectionHelper.java
@@ -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();
+ }
+}
diff --git a/common/src/main/java/com/hyperion/grabber/util/Preferences.kt b/common/src/main/java/com/hyperion/grabber/util/Preferences.kt
index cd981c6..a82da42 100644
--- a/common/src/main/java/com/hyperion/grabber/util/Preferences.kt
+++ b/common/src/main/java/com/hyperion/grabber/util/Preferences.kt
@@ -7,59 +7,54 @@ 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()
+
+ // ConcurrentHashMap forbids null values — never store nulls.
+ private val stringCache = ConcurrentHashMap()
private val intCache = ConcurrentHashMap()
private val boolCache = ConcurrentHashMap()
- private val cacheHits = ConcurrentHashMap()
+ private val nullStringKeys = ConcurrentHashMap.newKeySet()
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
}
-
- // Fetch from SharedPreferences and cache
+ stringCache[keyStr]?.let { return it }
+
val value = preferences.getString(keyStr, default)
- stringCache[keyStr] = value
+ 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){
+ 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){
+ if (it == 0) {
0
} else {
try {
@@ -75,33 +70,30 @@ class Preferences(context: Context) {
fun getInt(@StringRes keyResourceId: Int, default: Int = 0): Int {
val keyStr = key(keyResourceId)
-
- // Return from cache if available
- if (intCache.containsKey(keyStr)) {
- return intCache[keyStr]!!
+ 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
}
-
- val value = getString(keyResourceId)?.let { Integer.parseInt(it) } ?: default
intCache[keyStr] = value
return value
}
- fun putInt(@StringRes keyResourceId: Int, value: Int){
+ 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){
+ if (it == 0) {
false
} else {
try {
@@ -119,46 +111,39 @@ 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
return value
}
- fun putBoolean(@StringRes keyResourceId: Int, value: Boolean){
+ 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)
+ )
}
-
-}
\ No newline at end of file
+}
diff --git a/dist/apk/HyperionGrabber-3.0.1-mediacodec-debug.apk b/dist/apk/HyperionGrabber-3.0.1-mediacodec-debug.apk
new file mode 100644
index 0000000..8a20e24
Binary files /dev/null and b/dist/apk/HyperionGrabber-3.0.1-mediacodec-debug.apk differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 28d50ee..280f532 100755
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -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