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

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

No files matched your search

+291 -245
View File
@@ -20,133 +20,300 @@ import com.hyperion.grabber.common.util.HyperionGrabberOptions;
import java.nio.ByteBuffer;
public class HyperionScreenEncoder extends HyperionScreenEncoderBase {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public final class HyperionScreenEncoder extends HyperionScreenEncoderBase {
private static final String TAG = "HyperionScreenEncoder";
private static final boolean DEBUG = false;
private static final int MAX_IMAGE_READER_IMAGES = 2;
private static final int MAX_CAPTURE_WIDTH = 128;
private static final int MAX_CAPTURE_HEIGHT = 72;
// Constants
private static final int IMAGE_READER_IMAGES = 2;
private static final int BORDER_CHECK_FRAMES = 60;
private static final int BYTES_PER_PIXEL_RGBA = 4;
private static final int BYTES_PER_PIXEL_RGB = 3;
// Capture components
private VirtualDisplay mVirtualDisplay;
private ImageReader mImageReader;
private HandlerThread mCaptureThread;
private Handler mCaptureHandler;
private volatile boolean mRunning = false;
private volatile boolean mRunning;
private int mCaptureWidth;
private int mCaptureHeight;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
HyperionScreenEncoder(final HyperionThread.HyperionThreadListener listener,
final MediaProjection projection, final int width, final int height,
final int density, HyperionGrabberOptions options) {
super(listener, projection, width, height, density, options);
// Calculate capture dimensions maintaining aspect ratio
// Use very small resolution to minimize HDR tonemapping overhead
float aspectRatio = (float) width / height;
if (aspectRatio >= 1.0f) {
// Landscape
mCaptureWidth = Math.min(MAX_CAPTURE_WIDTH, getGrabberWidth());
mCaptureHeight = Math.max(1, (int) (mCaptureWidth / aspectRatio));
} else {
// Portrait
mCaptureHeight = Math.min(MAX_CAPTURE_HEIGHT, getGrabberHeight());
mCaptureWidth = Math.max(1, (int) (mCaptureHeight * aspectRatio));
private byte[] mRgbBuffer;
private byte[] mRowBuffer;
private final byte[] mAvgColorResult = new byte[3];
private int mBorderX;
private int mBorderY;
private int mFrameCount;
private final Runnable mCaptureRunnable = 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;
final long delayMs = Math.max(1L, mFrameIntervalMs - elapsedMs);
mCaptureHandler.postDelayed(this, delayMs);
}
}
// Ensure dimensions are even (required by some devices)
mCaptureWidth = (mCaptureWidth / 2) * 2;
mCaptureHeight = (mCaptureHeight / 2) * 2;
if (mCaptureWidth < 2) mCaptureWidth = 2;
if (mCaptureHeight < 2) mCaptureHeight = 2;
if (DEBUG) {
Log.d(TAG, "Capture dimensions: " + mCaptureWidth + "x" + mCaptureHeight);
};
private final long mFrameIntervalMs;
private final VirtualDisplay.Callback mDisplayCallback = new VirtualDisplay.Callback() {
@Override
public void onPaused() {
if (DEBUG) Log.d(TAG, "Display paused");
}
@Override
public void onResumed() {
if (DEBUG) Log.d(TAG, "Display resumed");
if (!mRunning) startCapture();
}
@Override
public void onStopped() {
if (DEBUG) Log.d(TAG, "Display stopped");
mRunning = false;
setCapturing(false);
}
};
/**
* Creates a new screen encoder.
*/
HyperionScreenEncoder(HyperionThread.HyperionThreadListener listener,
MediaProjection projection,
int screenWidth, int screenHeight,
int density,
HyperionGrabberOptions options) {
super(listener, projection, screenWidth, screenHeight, density, options);
mFrameIntervalMs = 1000L / mFrameRate;
initCaptureDimensions();
if (DEBUG) Log.d(TAG, "Capture: " + mCaptureWidth + "x" + mCaptureHeight + " @ " + mFrameRate + "fps");
try {
prepare();
init();
} catch (MediaCodec.CodecException e) {
e.printStackTrace();
Log.e(TAG, "Init failed", e);
}
}
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;
}
@TargetApi(Build.VERSION_CODES.M)
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void prepare() throws MediaCodec.CodecException {
if (DEBUG) Log.d(TAG, "Preparing encoder");
mCaptureThread = new HandlerThread(TAG + "-Capture", android.os.Process.THREAD_PRIORITY_BACKGROUND);
private void init() throws MediaCodec.CodecException {
mCaptureThread = new HandlerThread(TAG, android.os.Process.THREAD_PRIORITY_BACKGROUND);
mCaptureThread.start();
mCaptureHandler = new Handler(mCaptureThread.getLooper());
int displayFlags = DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC;
mImageReader = ImageReader.newInstance(
mCaptureWidth,
mCaptureHeight,
mCaptureWidth, mCaptureHeight,
PixelFormat.RGBA_8888,
MAX_IMAGE_READER_IMAGES
);
IMAGE_READER_IMAGES);
mMediaProjection.registerCallback(new MediaProjection.Callback() {
@Override
public void onStop() {
stopRecording();
}
}, mHandler);
mVirtualDisplay = mMediaProjection.createVirtualDisplay(
TAG,
mCaptureWidth, mCaptureHeight, mDensity,
displayFlags,
DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC,
mImageReader.getSurface(),
mDisplayCallback,
mHandler);
startCaptureLoop();
startCapture();
}
private void startCaptureLoop() {
private void startCapture() {
mRunning = true;
setCapturing(true);
mFrameCount = 0;
mCaptureHandler.post(mCaptureRunnable);
}
private void captureFrame() {
Image img = null;
try {
img = mImageReader.acquireLatestImage();
if (img != null) {
processImage(img);
}
} catch (Exception e) {
if (DEBUG) Log.w(TAG, "Capture error", e);
} finally {
if (img != null) {
img.close();
}
}
}
private void processImage(Image img) {
final Image.Plane[] planes = img.getPlanes();
if (planes.length == 0) return;
final long frameIntervalNs = 1_000_000_000L / mFrameRate;
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();
mCaptureHandler.post(new Runnable() {
@Override
public void run() {
if (!mRunning || !isCapturing()) {
return;
updateBorderDetection(buffer, width, height, rowStride, pixelStride);
if (mAvgColor) {
sendAverageColor(buffer, width, height, rowStride, pixelStride);
} else {
sendPixelData(buffer, width, height, rowStride, pixelStride);
}
}
private void updateBorderDetection(ByteBuffer buffer, int width, int height,
int rowStride, int pixelStride) {
if (!mRemoveBorders && !mAvgColor) return;
if (++mFrameCount >= BORDER_CHECK_FRAMES) {
mFrameCount = 0;
mBorderProcessor.parseBorder(buffer, width, height, rowStride, pixelStride);
final BorderProcessor.BorderObject border = mBorderProcessor.getCurrentBorder();
if (border != null && border.isKnown()) {
mBorderX = border.getHorizontalBorderIndex();
mBorderY = border.getVerticalBorderIndex();
}
}
}
private void sendPixelData(ByteBuffer buffer, int width, int height,
int rowStride, int pixelStride) {
final int bx = mBorderX;
final int by = mBorderY;
final int effWidth = width - (bx << 1);
final int effHeight = height - (by << 1);
if (effWidth <= 0 || effHeight <= 0) return;
final byte[] rgb = extractRgb(buffer, width, height, rowStride, pixelStride, bx, by, effWidth, effHeight);
mListener.sendFrame(rgb, effWidth, effHeight);
}
private byte[] extractRgb(ByteBuffer buffer, int width, int height,
int rowStride, int pixelStride,
int bx, int by, int effWidth, int effHeight) {
final int rgbSize = effWidth * effHeight * BYTES_PER_PIXEL_RGB;
if (mRgbBuffer == null || mRgbBuffer.length < rgbSize) {
mRgbBuffer = new byte[rgbSize];
}
final int endY = height - by;
final int endX = width - bx;
int rgbIdx = 0;
if (pixelStride == BYTES_PER_PIXEL_RGBA && rowStride == width * BYTES_PER_PIXEL_RGBA) {
final int rowBytes = effWidth * BYTES_PER_PIXEL_RGBA;
if (mRowBuffer == null || mRowBuffer.length < rowBytes) {
mRowBuffer = new byte[rowBytes];
}
final int savedPos = buffer.position();
for (int y = by; y < endY; y++) {
buffer.position(y * rowStride + bx * BYTES_PER_PIXEL_RGBA);
buffer.get(mRowBuffer, 0, rowBytes);
int i = 0;
final int unrollLimit = rowBytes - 15;
for (; i < unrollLimit; i += 16) {
mRgbBuffer[rgbIdx++] = mRowBuffer[i];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 1];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 2];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 4];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 5];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 6];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 8];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 9];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 10];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 12];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 13];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 14];
}
long startTime = System.nanoTime();
Image img = null;
try {
img = mImageReader.acquireLatestImage();
if (img != null) {
sendImage(img);
}
} catch (Exception e) {
if (DEBUG) Log.w(TAG, "Frame capture error: " + e.getMessage());
} finally {
if (img != null) {
try {
img.close();
} catch (Exception ignored) {}
}
}
long elapsed = System.nanoTime() - startTime;
long delayMs = Math.max(1, (frameIntervalNs - elapsed) / 1_000_000L);
if (mRunning && mCaptureHandler != null) {
mCaptureHandler.postDelayed(this, delayMs);
for (; i < rowBytes; i += BYTES_PER_PIXEL_RGBA) {
mRgbBuffer[rgbIdx++] = mRowBuffer[i];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 1];
mRgbBuffer[rgbIdx++] = mRowBuffer[i + 2];
}
}
});
buffer.position(savedPos);
} else {
for (int y = by; y < endY; y++) {
final int rowOff = y * rowStride;
for (int x = bx; x < endX; x++) {
final int off = rowOff + x * pixelStride;
mRgbBuffer[rgbIdx++] = buffer.get(off);
mRgbBuffer[rgbIdx++] = buffer.get(off + 1);
mRgbBuffer[rgbIdx++] = buffer.get(off + 2);
}
}
}
return mRgbBuffer;
}
private void sendAverageColor(ByteBuffer buffer, int width, int height,
int rowStride, int pixelStride) {
final int bx = mBorderX;
final int by = mBorderY;
final int startX = bx;
final int startY = by;
final int endX = width - bx;
final int endY = height - by;
if (endX <= startX || endY <= startY) return;
long r = 0, g = 0, b = 0;
int count = 0;
for (int y = startY; y < endY; y += 4) {
final int rowOff = y * rowStride;
for (int x = startX; x < endX; x += 4) {
final int off = rowOff + x * pixelStride;
r += buffer.get(off) & 0xFF;
g += buffer.get(off + 1) & 0xFF;
b += buffer.get(off + 2) & 0xFF;
count++;
}
}
if (count > 0) {
mAvgColorResult[0] = (byte) (r / count);
mAvgColorResult[1] = (byte) (g / count);
mAvgColorResult[2] = (byte) (b / count);
mListener.sendFrame(mAvgColorResult, 1, 1);
}
}
@Override
public void stopRecording() {
if (DEBUG) Log.i(TAG, "stopRecording Called");
if (DEBUG) Log.i(TAG, "Stopping");
mRunning = false;
setCapturing(false);
@@ -165,6 +332,12 @@ public class HyperionScreenEncoder extends HyperionScreenEncoderBase {
mCaptureHandler = null;
}
mRgbBuffer = null;
mRowBuffer = null;
mBorderX = 0;
mBorderY = 0;
mFrameCount = 0;
mHandler.getLooper().quit();
clearAndDisconnect();
@@ -176,177 +349,50 @@ public class HyperionScreenEncoder extends HyperionScreenEncoderBase {
@Override
public void resumeRecording() {
if (DEBUG) Log.i(TAG, "resumeRecording Called");
if (DEBUG) Log.i(TAG, "Resuming");
if (!isCapturing() && mImageReader != null) {
startCaptureLoop();
startCapture();
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void setOrientation(int orientation) {
if (mVirtualDisplay != null && orientation != mCurrentOrientation) {
mCurrentOrientation = orientation;
int temp = mCaptureWidth;
mCaptureWidth = mCaptureHeight;
mCaptureHeight = temp;
mRunning = false;
setCapturing(false);
if (mCaptureHandler != null) {
mCaptureHandler.removeCallbacksAndMessages(null);
}
mVirtualDisplay.resize(mCaptureWidth, mCaptureHeight, mDensity);
if (mImageReader != null) {
mImageReader.close();
}
mImageReader = ImageReader.newInstance(
mCaptureWidth,
mCaptureHeight,
PixelFormat.RGBA_8888,
MAX_IMAGE_READER_IMAGES
);
mVirtualDisplay.setSurface(mImageReader.getSurface());
startCaptureLoop();
if (mVirtualDisplay == null || orientation == mCurrentOrientation) return;
mCurrentOrientation = orientation;
mRunning = false;
setCapturing(false);
final int tmp = mCaptureWidth;
mCaptureWidth = mCaptureHeight;
mCaptureHeight = tmp;
if (mCaptureHandler != null) {
mCaptureHandler.removeCallbacksAndMessages(null);
}
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());
mRgbBuffer = null;
mRowBuffer = null;
startCapture();
}
private VirtualDisplay.Callback mDisplayCallback = new VirtualDisplay.Callback() {
@Override
public void onPaused() {
if (DEBUG) Log.d(TAG, "VirtualDisplay paused");
mRunning = false;
setCapturing(false);
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
@Override
public void onResumed() {
if (DEBUG) Log.d(TAG, "VirtualDisplay resumed");
if (!mRunning) {
startCaptureLoop();
}
}
@Override
public void onStopped() {
if (DEBUG) Log.d(TAG, "VirtualDisplay stopped");
mRunning = false;
setCapturing(false);
}
};
private byte[] getPixels(ByteBuffer buffer, int width, int height, int rowStride,
int pixelStride, int firstX, int firstY) {
int effectiveWidth = width - firstX * 2;
int effectiveHeight = height - firstY * 2;
if (effectiveWidth <= 0 || effectiveHeight <= 0) {
effectiveWidth = width;
effectiveHeight = height;
firstX = 0;
firstY = 0;
}
byte[] pixels = new byte[effectiveWidth * effectiveHeight * 3];
int pixelIndex = 0;
for (int y = firstY; y < height - firstY; y++) {
int rowOffset = y * rowStride;
for (int x = firstX; x < width - firstX; x++) {
int offset = rowOffset + x * pixelStride;
pixels[pixelIndex++] = (byte) (buffer.get(offset) & 0xff); // R
pixels[pixelIndex++] = (byte) (buffer.get(offset + 1) & 0xff); // G
pixels[pixelIndex++] = (byte) (buffer.get(offset + 2) & 0xff); // B
}
}
return pixels;
}
private byte[] getAverageColor(ByteBuffer buffer, int width, int height, int rowStride,
int pixelStride, int firstX, int firstY) {
long totalRed = 0, totalGreen = 0, totalBlue = 0;
int pixelCount = 0;
int startY = Math.max(0, firstY);
int endY = Math.min(height, height - firstY);
int startX = Math.max(0, firstX);
int endX = Math.min(width, width - firstX);
for (int y = startY; y < endY; y++) {
int rowOffset = y * rowStride;
for (int x = startX; x < endX; x++) {
int offset = rowOffset + x * pixelStride;
totalRed += buffer.get(offset) & 0xff;
totalGreen += buffer.get(offset + 1) & 0xff;
totalBlue += buffer.get(offset + 2) & 0xff;
pixelCount++;
}
}
byte[] avgColor = new byte[3];
if (pixelCount > 0) {
avgColor[0] = (byte) (totalRed / pixelCount);
avgColor[1] = (byte) (totalGreen / pixelCount);
avgColor[2] = (byte) (totalBlue / pixelCount);
}
return avgColor;
}
private void sendImage(Image img) {
if (img == null) return;
Image.Plane[] planes = img.getPlanes();
if (planes == null || planes.length == 0) return;
Image.Plane plane = planes[0];
ByteBuffer buffer = plane.getBuffer();
if (buffer == null) return;
int width = img.getWidth();
int height = img.getHeight();
int pixelStride = plane.getPixelStride();
int rowStride = plane.getRowStride();
int firstX = 0;
int firstY = 0;
if (mRemoveBorders || mAvgColor) {
mBorderProcessor.parseBorder(buffer, width, height, rowStride, pixelStride);
BorderProcessor.BorderObject border = mBorderProcessor.getCurrentBorder();
if (border != null && border.isKnown()) {
firstX = border.getHorizontalBorderIndex();
firstY = border.getVerticalBorderIndex();
}
}
try {
if (mAvgColor) {
mListener.sendFrame(
getAverageColor(buffer, width, height, rowStride, pixelStride, firstX, firstY),
1,
1
);
} else {
int effectiveWidth = width - firstX * 2;
int effectiveHeight = height - firstY * 2;
if (effectiveWidth > 0 && effectiveHeight > 0) {
mListener.sendFrame(
getPixels(buffer, width, height, rowStride, pixelStride, firstX, firstY),
effectiveWidth,
effectiveHeight
);
}
}
} catch (Exception e) {
if (DEBUG) Log.w(TAG, "Error sending frame: " + e.getMessage());
}
@Override
public void clearLights() {
super.clearLights();
}
}
@@ -11,134 +11,106 @@ import com.hyperion.grabber.common.network.HyperionThread;
import com.hyperion.grabber.common.util.BorderProcessor;
import com.hyperion.grabber.common.util.HyperionGrabberOptions;
public class HyperionScreenEncoderBase {
static final boolean DEBUG = false;
abstract class HyperionScreenEncoderBase {
private static final String TAG = "ScreenEncoderBase";
private final int CLEAR_COMMAND_DELAY_MS = 100;
private final int INIT_ORIENTATION;
static final boolean DEBUG = false;
private static final int CLEAR_DELAY_MS = 100;
final boolean mRemoveBorders = false; // enables detecting borders for standard grabbing - disabled for now
final boolean mAvgColor;
final int mWidthScaled;
final int mFrameRate;
final int mHeightScaled;
final int mDensity;
boolean mIsCapturing = false;
int mCurrentOrientation;
// Configuration (immutable after construction)
protected final int mDensity;
protected final int mFrameRate;
protected final boolean mAvgColor;
protected final boolean mRemoveBorders = false; // Disabled for now
private final int mInitOrientation;
private final int mWidthScaled;
private final int mHeightScaled;
BorderProcessor mBorderProcessor;
Handler mHandler;
MediaProjection mMediaProjection;
HyperionThread.HyperionThreadListener mListener;
HyperionScreenEncoderBase(final HyperionThread.HyperionThreadListener listener,
final MediaProjection projection, int width, int height,
final int density, HyperionGrabberOptions options) {
if (DEBUG) Log.d(TAG, "Encoder starting");
// Components
protected final MediaProjection mMediaProjection;
protected final HyperionThread.HyperionThreadListener mListener;
protected final BorderProcessor mBorderProcessor;
protected final Handler mHandler;
// Mutable state
protected volatile int mCurrentOrientation;
private volatile boolean mIsCapturing;
HyperionScreenEncoderBase(HyperionThread.HyperionThreadListener listener,
MediaProjection projection,
int width, int height,
int density,
HyperionGrabberOptions options) {
mListener = listener;
mMediaProjection = projection;
mDensity = density;
mFrameRate = options.getFrameRate();
mAvgColor = options.useAverageColor();
mBorderProcessor = new BorderProcessor(options.getBlackThreshold());
int blackThreshold = options.getBlackThreshold();
mBorderProcessor = new BorderProcessor(blackThreshold);
// Determine orientation
mCurrentOrientation = mInitOrientation =
width > height ? Configuration.ORIENTATION_LANDSCAPE : Configuration.ORIENTATION_PORTRAIT;
mCurrentOrientation = INIT_ORIENTATION = width > height ? Configuration.ORIENTATION_LANDSCAPE :
Configuration.ORIENTATION_PORTRAIT;
if (DEBUG) {
Log.d(TAG, "Density: " + String.valueOf(mDensity));
Log.d(TAG, "Frame Rate: " + String.valueOf(mFrameRate));
Log.d(TAG, "Original Width: " + String.valueOf(width));
Log.d(TAG, "Original Height: " + String.valueOf(height));
Log.d(TAG, "Average Color Only: " + String.valueOf(mAvgColor));
Log.d(TAG, "Black Pixel Threshold: " + String.valueOf(blackThreshold));
}
int divisor = options.findDivisor(width, height);
mHeightScaled = (height / divisor);
mWidthScaled = (width / divisor);
if (DEBUG) {
Log.d(TAG, "Common Divisor: " + String.valueOf(divisor));
Log.d(TAG, "Scaled Width: " + String.valueOf(mWidthScaled));
Log.d(TAG, "Scaled Height: " + String.valueOf(mHeightScaled));
}
// Calculate scaled dimensions
final int divisor = options.findDivisor(width, height);
mWidthScaled = width / divisor;
mHeightScaled = height / divisor;
// Handler thread for callbacks
final HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_DISPLAY);
thread.start();
mHandler = new Handler(thread.getLooper());
if (DEBUG) Log.d(TAG, "Encoder ready");
if (DEBUG) {
Log.d(TAG, "Init: " + width + "x" + height + " -> " + mWidthScaled + "x" + mHeightScaled);
}
}
private Runnable clearAndDisconnectRunner = new Runnable() {
public void run() {
if (DEBUG) Log.d(TAG, "Clearing LEDs and disconnecting");
try {
Thread.sleep(CLEAR_COMMAND_DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
mListener.clear();
mListener.disconnect();
}
};
private Runnable clearLightsRunner = new Runnable() {
public void run() {
if (DEBUG) Log.d(TAG, "Clearing LEDs");
try {
Thread.sleep(CLEAR_COMMAND_DELAY_MS);
} catch (InterruptedException e) {
e.printStackTrace();
}
mListener.clear();
}
};
public void clearLights() {
new Thread(clearLightsRunner).start();
new Thread(() -> {
sleep(CLEAR_DELAY_MS);
mListener.clear();
}).start();
}
void clearAndDisconnect() {
new Thread(clearAndDisconnectRunner).start();
protected void clearAndDisconnect() {
new Thread(() -> {
sleep(CLEAR_DELAY_MS);
mListener.clear();
mListener.disconnect();
}).start();
}
private static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public boolean isCapturing() {
return mIsCapturing;
}
public void setCapturing(boolean isCapturing) {
mIsCapturing = isCapturing;
protected void setCapturing(boolean capturing) {
mIsCapturing = capturing;
}
public void sendStatus() {
if (mListener != null) {
mListener.sendStatus(isCapturing());
}
mListener.sendStatus(mIsCapturing);
}
public void stopRecording() {
throw new RuntimeException("Stub!");
protected int getGrabberWidth() {
return mInitOrientation != mCurrentOrientation ? mHeightScaled : mWidthScaled;
}
public void resumeRecording() {
throw new RuntimeException("Stub!");
protected int getGrabberHeight() {
return mInitOrientation != mCurrentOrientation ? mWidthScaled : mHeightScaled;
}
int getGrabberWidth() {
return INIT_ORIENTATION != mCurrentOrientation ? mHeightScaled : mWidthScaled;
}
int getGrabberHeight() {
return INIT_ORIENTATION != mCurrentOrientation ? mWidthScaled : mHeightScaled;
}
public void setOrientation(int orientation) {
mCurrentOrientation = orientation;
}
}
public abstract void stopRecording();
public abstract void resumeRecording();
public abstract void setOrientation(int orientation);
}
@@ -1,6 +1,7 @@
package com.hyperion.grabber.common;
import android.annotation.TargetApi;
import android.app.ForegroundServiceStartNotAllowedException;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
@@ -12,7 +13,10 @@ import android.content.pm.ServiceInfo;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ServiceCompat;
@@ -24,6 +28,7 @@ import android.view.WindowManager;
import com.hyperion.grabber.common.network.HyperionThread;
import com.hyperion.grabber.common.util.HyperionGrabberOptions;
import com.hyperion.grabber.common.util.Preferences;
import com.hyperion.grabber.common.util.TclBypass;
import java.util.Objects;
@@ -31,8 +36,14 @@ public class HyperionScreenService extends Service {
public static final String BROADCAST_ERROR = "SERVICE_ERROR";
public static final String BROADCAST_TAG = "SERVICE_STATUS";
public static final String BROADCAST_FILTER = "SERVICE_FILTER";
public static final String BROADCAST_TCL_BLOCKED = "TCL_BLOCKED";
private static final boolean DEBUG = false;
private static final String TAG = "HyperionScreenService";
private boolean mForegroundFailed = false;
private boolean mTclBlocked = false;
private PowerManager.WakeLock mWakeLock;
private Handler mHandler;
private static final String BASE = "com.hyperion.grabber.service.";
public static final String ACTION_START = BASE + "ACTION_START";
@@ -43,38 +54,38 @@ public class HyperionScreenService extends Service {
private static final int NOTIFICATION_ID = 1;
private static final int NOTIFICATION_EXIT_INTENT_ID = 2;
private boolean RECONNECT = false;
private boolean hasConnected = false;
private boolean mReconnectEnabled = false;
private boolean mHasConnected = false;
private MediaProjectionManager mMediaProjectionManager;
private HyperionThread mHyperionThread;
private static MediaProjection _mediaProjection;
private static MediaProjection sMediaProjection;
private int mFrameRate;
private int mHorizontalLEDCount;
private int mVerticalLEDCount;
private boolean mSendAverageColor;
private boolean mWledEnabled;
private String mWledIp;
private HyperionScreenEncoder mHyperionEncoder;
private NotificationManager mNotificationManager;
private String mStartError = null;
HyperionThreadBroadcaster mReceiver = new HyperionThreadBroadcaster() {
private final HyperionThreadBroadcaster mReceiver = new HyperionThreadBroadcaster() {
@Override
public void onConnected() {
Log.d(TAG, "CONNECTED TO HYPERION INSTANCE");
hasConnected = true;
if (DEBUG) Log.d(TAG, "Connected to Hyperion server");
mHasConnected = true;
notifyActivity();
}
@Override
public void onConnectionError(int errorID, String error) {
Log.e(TAG, "COULD NOT CONNECT TO HYPERION INSTANCE");
if (error != null) Log.e(TAG, error);
if (!hasConnected) {
Log.e(TAG, "Connection error: " + (error != null ? error : "unknown"));
if (!mHasConnected) {
mStartError = getResources().getString(R.string.error_server_unreachable);
haltStartup();
}
if (RECONNECT && hasConnected) {
Log.e(TAG, "AUTOMATIC RECONNECT ENABLED. CONNECTING ...");
} else if (!RECONNECT && hasConnected) {
} else if (mReconnectEnabled) {
Log.i(TAG, "Attempting automatic reconnect...");
} else {
mStartError = getResources().getString(R.string.error_connection_lost);
stopSelf();
}
@@ -82,8 +93,7 @@ public class HyperionScreenService extends Service {
@Override
public void onReceiveStatus(boolean isCapturing) {
if (DEBUG) Log.v(TAG, "Received grabber status, notifying activity. Status: " +
String.valueOf(isCapturing));
if (DEBUG) Log.v(TAG, "Received status: capturing=" + isCapturing);
notifyActivity();
}
};
@@ -126,6 +136,14 @@ public class HyperionScreenService extends Service {
@Override
public void onCreate() {
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mHandler = new Handler(Looper.getMainLooper());
// Try shell bypass on startup for TCL devices
if (TclBypass.isTclDevice() || TclBypass.isRestrictedManufacturer()) {
Log.i(TAG, "Detected restricted manufacturer, attempting shell bypass");
TclBypass.tryShellBypass(this);
}
super.onCreate();
}
@@ -139,23 +157,34 @@ public class HyperionScreenService extends Service {
mHorizontalLEDCount = prefs.getInt(R.string.pref_key_x_led);
mVerticalLEDCount = prefs.getInt(R.string.pref_key_y_led);
mSendAverageColor = prefs.getBoolean(R.string.pref_key_use_avg_color);
RECONNECT = prefs.getBoolean(R.string.pref_key_reconnect);
mReconnectEnabled = prefs.getBoolean(R.string.pref_key_reconnect);
mWledEnabled = prefs.getBoolean(R.string.pref_key_wled_enabled);
mWledIp = prefs.getString(R.string.pref_key_wled_ip, null);
int delay = prefs.getInt(R.string.pref_key_reconnect_delay);
if (host == null || Objects.equals(host, "0.0.0.0") || Objects.equals(host, "")) {
mStartError = getResources().getString(R.string.error_empty_host);
return false;
}
if (port == -1) {
mStartError = getResources().getString(R.string.error_empty_port);
return false;
if (!mWledEnabled) {
if (host == null || Objects.equals(host, "0.0.0.0") || Objects.equals(host, "")) {
mStartError = getResources().getString(R.string.error_empty_host);
return false;
}
if (port == -1) {
mStartError = getResources().getString(R.string.error_empty_port);
return false;
}
} else {
if (mWledIp == null || Objects.equals(mWledIp, "0.0.0.0") || Objects.equals(mWledIp, "")) {
mStartError = "WLED IP should not be empty";
return false;
}
}
if (mHorizontalLEDCount <= 0 || mVerticalLEDCount <= 0) {
mStartError = getResources().getString(R.string.error_invalid_led_counts);
return false;
}
mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
mHyperionThread = new HyperionThread(mReceiver, host, port, Integer.parseInt(priority), RECONNECT, delay);
int priorityValue = Integer.parseInt(priority);
mHyperionThread = new HyperionThread(mReceiver, host, port, priorityValue, mReconnectEnabled, delay, mWledEnabled, mWledIp);
mHyperionThread.start();
mStartError = null;
return true;
@@ -177,15 +206,20 @@ public class HyperionScreenService extends Service {
if (mHyperionThread == null) {
boolean isPrepared = prepared();
if (isPrepared) {
// For Android 12+, we must start foreground with mediaProjection type BEFORE getting MediaProjection
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceCompat.startForeground(this, NOTIFICATION_ID, getNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
} else {
startForeground(NOTIFICATION_ID, getNotification());
boolean foregroundStarted = tryStartForeground();
if (!foregroundStarted && mTclBlocked) {
acquireWakeLock();
}
startScreenRecord(intent);
try {
startScreenRecord(intent);
} catch (SecurityException e) {
Log.e(TAG, "Failed to start screen recording: " + e.getMessage());
mStartError = getResources().getString(R.string.error_media_projection_denied);
haltStartup();
break;
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
@@ -234,20 +268,113 @@ public class HyperionScreenService extends Service {
if (DEBUG) Log.v(TAG, "Wake receiver not registered");
}
releaseWakeLock();
stopScreenRecord();
stopForeground(true);
notifyActivity();
super.onDestroy();
}
private boolean tryStartForeground() {
mForegroundFailed = false;
mTclBlocked = false;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceCompat.startForeground(this, NOTIFICATION_ID, getNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
} else {
startForeground(NOTIFICATION_ID, getNotification());
}
return true;
} catch (Exception e) {
Log.e(TAG, "Foreground start failed: " + e.getMessage());
mForegroundFailed = true;
String msg = e.getMessage();
if (msg != null && (msg.contains("TclAppBoot") || msg.contains("forbid"))) {
mTclBlocked = true;
}
}
if (mForegroundFailed) {
try {
Thread.sleep(100);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceCompat.startForeground(this, NOTIFICATION_ID, getNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
} else {
startForeground(NOTIFICATION_ID, getNotification());
}
mForegroundFailed = false;
mTclBlocked = false;
return true;
} catch (Exception e) {
Log.e(TAG, "Foreground retry failed: " + e.getMessage());
mTclBlocked = true;
}
}
notifyTclBlocked();
return false;
}
private void acquireWakeLock() {
if (mWakeLock == null) {
try {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm != null) {
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"HyperionGrabber::ScreenCapture");
mWakeLock.acquire(60 * 60 * 1000L);
}
} catch (Exception e) {
Log.e(TAG, "Failed to acquire wake lock", e);
}
}
}
private void releaseWakeLock() {
if (mWakeLock != null && mWakeLock.isHeld()) {
try {
mWakeLock.release();
Log.i(TAG, "Wake lock released");
} catch (Exception e) {
Log.e(TAG, "Failed to release wake lock", e);
}
mWakeLock = null;
}
}
private void notifyTclBlocked() {
Intent intent = new Intent(BROADCAST_FILTER);
intent.putExtra(BROADCAST_TAG, false);
intent.putExtra(BROADCAST_TCL_BLOCKED, true);
intent.putExtra(BROADCAST_ERROR, "Foreground service blocked by device manufacturer");
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
private void haltStartup() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceCompat.startForeground(this, NOTIFICATION_ID, getNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
} else {
startForeground(NOTIFICATION_ID, getNotification());
// Try to start foreground to show error, but don't fail if blocked
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceCompat.startForeground(this, NOTIFICATION_ID, getNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
} else {
startForeground(NOTIFICATION_ID, getNotification());
}
} catch (Exception e) {
Log.w(TAG, "Could not start foreground during halt: " + e.getMessage());
}
notifyActivity();
if (mHyperionThread != null) {
mHyperionThread.interrupt();
mHyperionThread = null;
}
stopSelf();
}
@@ -267,45 +394,55 @@ public class HyperionScreenService extends Service {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void startScreenRecord(final Intent intent) {
if (DEBUG) Log.v(TAG, "Start screen recorder");
if (DEBUG) Log.v(TAG, "Starting screen recorder");
final int resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0);
// get MediaProjection
final MediaProjection projection = mMediaProjectionManager.getMediaProjection(resultCode, intent);
WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
if (projection != null && window != null) {
_mediaProjection = projection;
sMediaProjection = projection;
final DisplayMetrics metrics = new DisplayMetrics();
window.getDefaultDisplay().getRealMetrics(metrics);
final int density = metrics.densityDpi;
HyperionGrabberOptions options = new HyperionGrabberOptions(mHorizontalLEDCount,
mVerticalLEDCount, mFrameRate, mSendAverageColor);
if (DEBUG) Log.v(TAG, "Starting the recorder");
mHyperionEncoder = new HyperionScreenEncoder(mHyperionThread.getReceiver(),
projection, metrics.widthPixels, metrics.heightPixels,
density, options);
HyperionGrabberOptions options = new HyperionGrabberOptions(
mHorizontalLEDCount, mVerticalLEDCount, mFrameRate, mSendAverageColor);
if (DEBUG) Log.v(TAG, "Creating encoder: " + metrics.widthPixels + "x" + metrics.heightPixels);
mHyperionEncoder = new HyperionScreenEncoder(
mHyperionThread.getReceiver(),
projection,
metrics.widthPixels,
metrics.heightPixels,
metrics.densityDpi,
options);
mHyperionEncoder.sendStatus();
}
}
private void stopScreenRecord() {
if (DEBUG) Log.v(TAG, "Stop screen recorder");
RECONNECT = false;
if (DEBUG) Log.v(TAG, "Stopping screen recorder");
mReconnectEnabled = false;
mNotificationManager.cancel(NOTIFICATION_ID);
if (mHyperionEncoder != null) {
if (DEBUG) Log.v(TAG, "Stopping the current encoder");
if (DEBUG) Log.v(TAG, "Stopping encoder");
mHyperionEncoder.stopRecording();
mHyperionEncoder = null;
}
releaseResource();
if (mHyperionThread != null) {
mHyperionThread.interrupt();
mHyperionThread = null;
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void releaseResource() {
if (_mediaProjection != null) {
_mediaProjection.stop();
_mediaProjection = null;
private void releaseResource() {
if (sMediaProjection != null) {
sMediaProjection.stop();
sMediaProjection = null;
}
}
@@ -314,7 +451,7 @@ public class HyperionScreenService extends Service {
}
boolean isCommunicating() {
return isCapturing() && hasConnected;
return isCapturing() && mHasConnected;
}
private void notifyActivity() {
@@ -322,11 +459,8 @@ public class HyperionScreenService extends Service {
intent.putExtra(BROADCAST_TAG, isCommunicating());
intent.putExtra(BROADCAST_ERROR, mStartError);
if (DEBUG) {
Log.v(TAG, "Sending status broadcast - communicating: " +
String.valueOf(isCommunicating()));
if (mStartError != null) {
Log.v(TAG, "Startup error: " + mStartError);
}
Log.v(TAG, "Broadcasting status: communicating=" + isCommunicating() +
(mStartError != null ? ", error=" + mStartError : ""));
}
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
@@ -0,0 +1,173 @@
package com.hyperion.grabber.common.util;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
import java.util.List;
public class TclBypass {
private static final String TAG = "TclBypass";
public static boolean isTclDevice() {
String manufacturer = Build.MANUFACTURER.toLowerCase();
String brand = Build.BRAND.toLowerCase();
String device = Build.DEVICE.toLowerCase();
String model = Build.MODEL.toLowerCase();
return manufacturer.contains("tcl") ||
brand.contains("tcl") ||
device.startsWith("g10") ||
model.contains("tcl") ||
model.contains("smart tv");
}
public static boolean isRestrictedManufacturer() {
String manufacturer = Build.MANUFACTURER.toLowerCase();
return manufacturer.contains("tcl") ||
manufacturer.contains("xiaomi") ||
manufacturer.contains("huawei") ||
manufacturer.contains("oppo") ||
manufacturer.contains("vivo") ||
manufacturer.contains("realme") ||
manufacturer.contains("samsung");
}
public static boolean openTclAutoStartSettings(Context context) {
Intent[] intents = {
// TCL specific intents
new Intent().setComponent(new ComponentName("com.tcl.guard",
"com.tcl.guard.activity.AutostartActivity")),
new Intent().setComponent(new ComponentName("com.tcl.guard",
"com.tcl.guard.activity.AppAutoStartManagerActivity")),
new Intent().setComponent(new ComponentName("com.android.settings",
"com.tcl.settings.TclAutoStartSettingsActivity")),
new Intent().setComponent(new ComponentName("com.tcl.tvweishi",
"com.tcl.tvweishi.settings.AutoBootManageActivity")),
// TCL TV Settings
new Intent().setComponent(new ComponentName("com.android.tv.settings",
"com.android.tv.settings.MainSettings")),
new Intent().setComponent(new ComponentName("com.android.tv.settings",
"com.android.tv.settings.device.apps.AppsActivity")),
// Generic auto-start intents
new Intent("android.settings.APPLICATION_DEVELOPMENT_SETTINGS"),
new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
.setData(Uri.parse("package:" + context.getPackageName())),
};
for (Intent intent : intents) {
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (isIntentAvailable(context, intent)) {
context.startActivity(intent);
Log.d(TAG, "Opened: " + intent.getComponent());
return true;
}
} catch (Exception e) {
Log.d(TAG, "Failed to open: " + intent, e);
}
}
return false;
}
public static boolean openSpecialAppAccess(Context context) {
Intent[] intents = {
// Special app access
new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
.setData(Uri.parse("package:" + context.getPackageName())),
new Intent("android.settings.action.MANAGE_OVERLAY_PERMISSION")
.setData(Uri.parse("package:" + context.getPackageName())),
// TV Settings apps section
new Intent().setComponent(new ComponentName("com.android.tv.settings",
"com.android.tv.settings.device.apps.AppManagementActivity"))
.putExtra("packageName", context.getPackageName()),
};
for (Intent intent : intents) {
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (isIntentAvailable(context, intent)) {
context.startActivity(intent);
return true;
}
} catch (Exception e) {
Log.d(TAG, "Failed: " + intent, e);
}
}
return false;
}
public static void tryShellBypass(Context context) {
new Thread(() -> {
String pkg = context.getPackageName();
String[] commands = {
"appops set " + pkg + " PROJECT_MEDIA allow",
"appops set " + pkg + " android:project_media allow",
"appops set " + pkg + " SYSTEM_ALERT_WINDOW allow",
"settings put global auto_start_" + pkg + " 1",
"settings put secure auto_start_" + pkg + " 1",
"am broadcast -a com.tcl.action.ALLOW_AUTO_START -e package " + pkg,
"am broadcast -a com.tcl.appboot.action.SET_ALLOW -e package " + pkg,
"settings put global tcl_app_boot_" + pkg + " allow",
"settings put secure tcl_app_boot_" + pkg + " allow",
"cmd deviceidle whitelist +" + pkg,
"dumpsys deviceidle whitelist +" + pkg,
"appops set " + pkg + " RUN_IN_BACKGROUND allow",
"appops set " + pkg + " RUN_ANY_IN_BACKGROUND allow",
"appops set " + pkg + " START_FOREGROUND allow",
"appops set " + pkg + " INSTANT_APP_START_FOREGROUND allow",
};
for (String cmd : commands) {
try {
Process process = Runtime.getRuntime().exec(new String[]{"sh", "-c", cmd});
process.waitFor();
int exit = process.exitValue();
if (exit == 0) {
Log.d(TAG, "Success: " + cmd);
}
} catch (Exception e) {
}
}
}).start();
}
public static void showTclHelpDialog(Activity activity, Runnable onRetry) {
String pkg = activity.getPackageName();
String message = "Your TV is blocking the screen recording service.\n\n" +
"USE ADB TO FIX (from computer):\n\n" +
"adb shell appops set " + pkg + " PROJECT_MEDIA allow\n\n" +
"adb shell appops set " + pkg + " START_FOREGROUND allow\n\n" +
"Or reinstall with permissions:\n" +
"adb install -g -r hyperion.apk";
new AlertDialog.Builder(activity)
.setTitle("TCL Blocked")
.setMessage(message)
.setPositiveButton("Retry", (d, w) -> {
tryShellBypass(activity);
if (onRetry != null) {
activity.getWindow().getDecorView().postDelayed(() -> onRetry.run(), 1000);
}
})
.setNegativeButton("Close", null)
.setCancelable(true)
.show();
}
private static boolean isIntentAvailable(Context context, Intent intent) {
PackageManager pm = context.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list != null && !list.isEmpty();
}
}
@@ -1,14 +0,0 @@
package com.hyperion.grabber.common.network;
import java.io.IOException;
public interface HyperionClient {
boolean isConnected();
void disconnect() throws IOException;
void clear(int priority) throws IOException;
void clearAll() throws IOException;
void setColor(int color, int priority) throws IOException;
void setColor(int color, int priority, int duration_ms) throws IOException;
void setImage(byte[] data, int width, int height, int priority) throws IOException;
void setImage(byte[] data, int width, int height, int priority, int duration_ms) throws IOException;
}
@@ -0,0 +1,28 @@
package com.hyperion.grabber.common.network
import java.io.IOException
interface HyperionClient {
fun isConnected(): Boolean
@Throws(IOException::class)
fun disconnect()
@Throws(IOException::class)
fun clear(priority: Int)
@Throws(IOException::class)
fun clearAll()
@Throws(IOException::class)
fun setColor(color: Int, priority: Int)
@Throws(IOException::class)
fun setColor(color: Int, priority: Int, duration_ms: Int)
@Throws(IOException::class)
fun setImage(data: ByteArray, width: Int, height: Int, priority: Int)
@Throws(IOException::class)
fun setImage(data: ByteArray, width: Int, height: Int, priority: Int, duration_ms: Int)
}
@@ -1,137 +0,0 @@
package com.hyperion.grabber.common.network;
import com.google.flatbuffers.FlatBufferBuilder;
import hyperionnet.Clear;
import hyperionnet.Color;
import hyperionnet.Command;
import hyperionnet.Image;
import hyperionnet.ImageType;
import hyperionnet.RawImage;
import hyperionnet.Register;
import hyperionnet.Reply;
import hyperionnet.Request;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
public class HyperionFlatBuffers implements HyperionClient {
private final int TIMEOUT = 1000;
private final Socket mSocket;
private final int mPriority;
private final FlatBufferBuilder mBuilder;
public HyperionFlatBuffers(String address, int port, int priority) throws IOException {
mSocket = new Socket();
mSocket.connect(new InetSocketAddress(address, port), TIMEOUT);
mPriority = priority;
mBuilder = new FlatBufferBuilder(1024);
register();
}
private void register() throws IOException {
mBuilder.clear();
int originOffset = mBuilder.createString("HyperionAndroidGrabber");
int registerOffset = Register.createRegister(mBuilder, originOffset, mPriority);
int requestOffset = Request.createRequest(mBuilder, Command.Register, registerOffset);
Request.finishRequestBuffer(mBuilder, requestOffset);
sendRequest(mBuilder.dataBuffer());
}
@Override
public boolean isConnected() {
return mSocket != null && mSocket.isConnected();
}
@Override
public void disconnect() throws IOException {
if (isConnected()) {
mSocket.close();
}
}
@Override
public void clear(int priority) throws IOException {
mBuilder.clear();
int clearOffset = Clear.createClear(mBuilder, priority);
int requestOffset = Request.createRequest(mBuilder, Command.Clear, clearOffset);
Request.finishRequestBuffer(mBuilder, requestOffset);
sendRequest(mBuilder.dataBuffer());
}
@Override
public void clearAll() throws IOException {
clear(-1);
}
@Override
public void setColor(int color, int priority) throws IOException {
setColor(color, priority, -1);
}
@Override
public void setColor(int color, int priority, int duration_ms) throws IOException {
mBuilder.clear();
int colorOffset = Color.createColor(mBuilder, color, duration_ms);
int requestOffset = Request.createRequest(mBuilder, Command.Color, colorOffset);
Request.finishRequestBuffer(mBuilder, requestOffset);
sendRequest(mBuilder.dataBuffer());
}
@Override
public void setImage(byte[] data, int width, int height, int priority) throws IOException {
setImage(data, width, height, priority, -1);
}
@Override
public void setImage(byte[] data, int width, int height, int priority, int duration_ms) throws IOException {
mBuilder.clear();
int dataOffset = RawImage.createDataVector(mBuilder, data);
int rawImageOffset = RawImage.createRawImage(mBuilder, dataOffset, width, height);
int imageOffset = Image.createImage(mBuilder, ImageType.RawImage, rawImageOffset, duration_ms);
int requestOffset = Request.createRequest(mBuilder, Command.Image, imageOffset);
Request.finishRequestBuffer(mBuilder, requestOffset);
sendRequest(mBuilder.dataBuffer());
}
private void sendRequest(ByteBuffer bb) throws IOException {
if (isConnected()) {
int size = bb.remaining();
byte[] header = new byte[4];
header[0] = (byte)((size >> 24) & 0xFF);
header[1] = (byte)((size >> 16) & 0xFF);
header[2] = (byte)((size >> 8) & 0xFF);
header[3] = (byte)((size ) & 0xFF);
OutputStream output = mSocket.getOutputStream();
output.write(header);
byte[] data = new byte[bb.remaining()];
bb.get(data);
output.write(data);
output.flush();
receiveReply();
}
}
private void receiveReply() throws IOException {
// We don't really need to parse the reply for now, but we should consume it
// to keep the socket clean.
if (mSocket.getInputStream().available() >= 4) {
byte[] header = new byte[4];
int read = mSocket.getInputStream().read(header, 0, 4);
if (read == 4) {
int size = ((header[0] & 0xFF) << 24) | ((header[1] & 0xFF) << 16) | ((header[2] & 0xFF) << 8) | (header[3] & 0xFF);
if (size > 0) {
byte[] data = new byte[size];
mSocket.getInputStream().read(data, 0, size);
// Reply reply = Reply.getRootAsReply(ByteBuffer.wrap(data));
}
}
}
}
}
@@ -0,0 +1,145 @@
package com.hyperion.grabber.common.network
import com.google.flatbuffers.FlatBufferBuilder
import hyperionnet.*
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket
import java.nio.ByteBuffer
class HyperionFlatBuffers(address: String?, port: Int, priority: Int) : HyperionClient {
private val TIMEOUT = 1000
private val mSocket: Socket = Socket()
private val mPriority: Int
private val mBuilder: FlatBufferBuilder
init {
mSocket.tcpNoDelay = true // Disable Nagle's algorithm for low latency
mSocket.sendBufferSize = 8192 // Smaller buffer for faster sends
mSocket.receiveBufferSize = 4096
mSocket.connect(InetSocketAddress(address, port), TIMEOUT)
mSocket.soTimeout = 10 // Very short timeout for non-blocking behavior
mPriority = priority
mBuilder = FlatBufferBuilder(1024)
register()
}
@Throws(IOException::class)
private fun register() {
mBuilder.clear()
val originOffset = mBuilder.createString("HyperionAndroidGrabber")
val registerOffset = Register.createRegister(mBuilder, originOffset, mPriority)
val requestOffset = Request.createRequest(mBuilder, Command.Register, registerOffset)
Request.finishRequestBuffer(mBuilder, requestOffset)
sendRequest(mBuilder.dataBuffer())
}
override fun isConnected(): Boolean {
return mSocket.isConnected
}
@Throws(IOException::class)
override fun disconnect() {
if (isConnected()) {
mSocket.close()
}
}
@Throws(IOException::class)
override fun clear(priority: Int) {
mBuilder.clear()
val clearOffset = Clear.createClear(mBuilder, priority)
val requestOffset = Request.createRequest(mBuilder, Command.Clear, clearOffset)
Request.finishRequestBuffer(mBuilder, requestOffset)
sendRequest(mBuilder.dataBuffer())
}
@Throws(IOException::class)
override fun clearAll() {
clear(-1)
}
@Throws(IOException::class)
override fun setColor(color: Int, priority: Int) {
setColor(color, priority, -1)
}
@Throws(IOException::class)
override fun setColor(color: Int, priority: Int, duration_ms: Int) {
mBuilder.clear()
val colorOffset = Color.createColor(mBuilder, color, duration_ms)
val requestOffset = Request.createRequest(mBuilder, Command.Color, colorOffset)
Request.finishRequestBuffer(mBuilder, requestOffset)
sendRequest(mBuilder.dataBuffer())
}
@Throws(IOException::class)
override fun setImage(data: ByteArray, width: Int, height: Int, priority: Int) {
setImage(data, width, height, priority, -1)
}
@Throws(IOException::class)
override fun setImage(data: ByteArray, width: Int, height: Int, priority: Int, duration_ms: Int) {
mBuilder.clear()
val dataOffset = RawImage.createDataVector(mBuilder, data)
val rawImageOffset = RawImage.createRawImage(mBuilder, dataOffset, width, height)
val imageOffset = Image.createImage(mBuilder, ImageType.RawImage, rawImageOffset, duration_ms)
val requestOffset = Request.createRequest(mBuilder, Command.Image, imageOffset)
Request.finishRequestBuffer(mBuilder, requestOffset)
sendRequest(mBuilder.dataBuffer())
}
@Throws(IOException::class)
private fun sendRequest(bb: ByteBuffer) {
if (isConnected()) {
val size = bb.remaining()
val header = ByteArray(4)
header[0] = ((size shr 24) and 0xFF).toByte()
header[1] = ((size shr 16) and 0xFF).toByte()
header[2] = ((size shr 8) and 0xFF).toByte()
header[3] = (size and 0xFF).toByte()
val output = mSocket.getOutputStream()
output.write(header)
val data = ByteArray(bb.remaining())
bb[data]
output.write(data)
output.flush()
// Don't wait for reply - fire and forget for minimal latency
// Replies will be handled asynchronously if needed
}
}
fun cleanReplies() {
receiveReply()
}
private fun receiveReply() {
// Non-blocking reply consumption to keep socket clean
// This is called separately and doesn't block frame sending
try {
while (mSocket.getInputStream().available() >= 4) {
val header = ByteArray(4)
val read = mSocket.getInputStream().read(header, 0, 4)
if (read == 4) {
val size = (header[0].toInt() and 0xFF shl 24) or
(header[1].toInt() and 0xFF shl 16) or
(header[2].toInt() and 0xFF shl 8) or
(header[3].toInt() and 0xFF)
if (size > 0 && mSocket.getInputStream().available() >= size) {
val data = ByteArray(size)
mSocket.getInputStream().read(data, 0, size)
} else {
break // Not enough data yet, will consume later
}
} else {
break
}
}
} catch (e: IOException) {
// Ignore - non-blocking read
}
}
}
@@ -1,124 +0,0 @@
package com.hyperion.grabber.common.network;
import com.hyperion.grabber.common.HyperionScreenService;
import java.io.IOException;
public class HyperionThread extends Thread {
private String HOST;
private int PORT;
private int PRIORITY;
private final int FRAME_DURATION = -1;
private boolean RECONNECT = false;
private boolean HAS_CONNECTED = false;
private int RECONNECT_DELAY;
private HyperionClient mHyperion;
HyperionScreenService.HyperionThreadBroadcaster mSender;
HyperionThreadListener mReceiver = new HyperionThreadListener() {
@Override
public void sendFrame(byte[] data, int width, int height) {
if (mHyperion != null && mHyperion.isConnected()) {
try {
mHyperion.setImage(data, width, height, PRIORITY, FRAME_DURATION);
} catch (IOException e) {
mSender.onConnectionError(e.hashCode(), e.getMessage());
e.printStackTrace();
if (RECONNECT && HAS_CONNECTED) {
reconnectDelay(RECONNECT_DELAY);
try {
mHyperion = createClient();
} catch (IOException i) {
i.printStackTrace();
}
}
}
}
}
@Override
public void clear() {
if (mHyperion != null && mHyperion.isConnected()) {
try {
mHyperion.clear(PRIORITY);
} catch (IOException e) {
mSender.onConnectionError(e.hashCode(), e.getMessage());
e.printStackTrace();
}
}
}
@Override
public void disconnect() {
if (mHyperion != null) {
try {
mHyperion.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void sendStatus(boolean isGrabbing) {
if (mSender != null) {
mSender.onReceiveStatus(isGrabbing);
}
}
};
public HyperionThread(HyperionScreenService.HyperionThreadBroadcaster listener, final String host,
final int port, final int priority, final boolean reconnect, final int delay){
HOST = host;
PORT = port;
PRIORITY = priority;
RECONNECT = reconnect;
RECONNECT_DELAY = delay * 1000;
mSender = listener;
}
public HyperionThreadListener getReceiver() {return mReceiver;}
private HyperionClient createClient() throws IOException {
return new HyperionFlatBuffers(HOST, PORT, PRIORITY);
}
@Override
public void run(){
do {
try {
mHyperion = createClient();
} catch (IOException e) {
mSender.onConnectionError(e.hashCode(), e.getMessage());
e.printStackTrace();
if (RECONNECT && HAS_CONNECTED) {
reconnectDelay(RECONNECT_DELAY);
}
} finally {
if (mHyperion != null && mSender != null && mHyperion.isConnected()) {
HAS_CONNECTED = true;
mSender.onConnected();
break;
}
}
} while (RECONNECT && HAS_CONNECTED);
}
public void reconnectDelay(long t) {
try {
Thread.sleep(t);
} catch (InterruptedException e) {
RECONNECT = false;
HAS_CONNECTED = false;
Thread.currentThread().interrupt();
}
}
public interface HyperionThreadListener {
void sendFrame(byte[] data, int width, int height);
void clear();
void disconnect();
void sendStatus(boolean isGrabbing);
}
}
@@ -0,0 +1,182 @@
package com.hyperion.grabber.common.network
import com.hyperion.grabber.common.HyperionScreenService.HyperionThreadBroadcaster
import java.io.IOException
import java.net.InetAddress
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
class HyperionThread(
private val callback: HyperionThreadBroadcaster,
private val host: String?,
private val port: Int,
private val priority: Int,
reconnect: Boolean,
delaySeconds: Int,
private val wledEnabled: Boolean,
private val wledIp: String?
) : Thread(TAG) {
private val reconnectDelayMs = (delaySeconds * 1000).toLong()
private val reconnectEnabled = AtomicBoolean(reconnect)
private val connected = AtomicBoolean(false)
private val clientRef = AtomicReference<HyperionClient>()
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
@Volatile
private var pendingTask: Future<*>? = null
@Volatile
private var pendingFrame: FrameData? = null
val receiver: HyperionThreadListener = object : HyperionThreadListener {
override fun sendFrame(data: ByteArray, width: Int, height: Int) {
val client = clientRef.get()
if (client == null || !client.isConnected()) return
pendingFrame = FrameData(data, width, height)
val pending = pendingTask
if (pending != null && !pending.isDone) {
pending.cancel(false)
}
pendingTask = executor.submit { sendPendingFrame() }
}
private fun sendPendingFrame() {
val frame = pendingFrame
val client = clientRef.get()
if (frame == null || client == null || !client.isConnected()) return
try {
client.setImage(frame.data, frame.width, frame.height, priority, FRAME_DURATION)
if (client is HyperionFlatBuffers) {
client.cleanReplies()
}
} catch (e: IOException) {
handleError(e)
}
}
override fun clear() {
val client = clientRef.get()
if (client != null && client.isConnected()) {
try {
client.clear(priority)
} catch (e: IOException) {
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error")
}
}
}
override fun disconnect() {
val pending = pendingTask
if (pending != null) {
pending.cancel(true)
pendingTask = null
}
pendingFrame = null
if (!executor.isShutdown) {
executor.shutdownNow()
try {
executor.awaitTermination(SHUTDOWN_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS)
} catch (e: InterruptedException) {
currentThread().interrupt()
}
}
val client = clientRef.getAndSet(null)
if (client != null) {
try {
client.disconnect()
} catch (ignored: IOException) {
}
}
connected.set(false)
}
override fun sendStatus(isGrabbing: Boolean) {
callback.onReceiveStatus(isGrabbing)
}
}
override fun run() {
connect()
}
private fun createClient(): HyperionClient {
return if (wledEnabled && wledIp != null) {
WledDdpClient(InetAddress.getByName(wledIp), 4048)
} else {
HyperionFlatBuffers(host, port, priority)
}
}
private fun connect() {
do {
try {
val client = createClient()
if (client.isConnected()) {
clientRef.set(client)
connected.set(true)
callback.onConnected()
return
}
} catch (e: IOException) {
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error")
if (reconnectEnabled.get() && connected.get()) {
sleepSafe(reconnectDelayMs)
}
}
} while (reconnectEnabled.get() && connected.get())
}
private fun handleError(e: IOException) {
callback.onConnectionError(e.hashCode(), e.message ?: "Unknown error")
if (reconnectEnabled.get() && connected.get()) {
sleepSafe(reconnectDelayMs)
try {
val newClient = createClient()
if (newClient.isConnected()) {
clientRef.set(newClient)
}
} catch (ignored: IOException) {
}
}
}
private fun sleepSafe(ms: Long) {
try {
sleep(ms)
} catch (e: InterruptedException) {
reconnectEnabled.set(false)
connected.set(false)
currentThread().interrupt()
}
}
private class FrameData(val data: ByteArray, val width: Int, val height: Int)
interface HyperionThreadListener {
fun sendFrame(data: ByteArray, width: Int, height: Int)
fun clear()
fun disconnect()
fun sendStatus(isGrabbing: Boolean)
}
companion object {
private const val TAG = "HyperionThread"
private const val FRAME_DURATION = -1
private const val SHUTDOWN_TIMEOUT_MS = 100
}
}
@@ -1,171 +0,0 @@
package com.hyperion.grabber.common.network;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;
import android.util.Log;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/** Scans the local network for running Hyperion servers
* Created by nino on 27-5-18.
*/
public class NetworkScanner {
public static final int PORT = 19400;
/** The amount of milliseconds we try to connect to a given ip before giving up */
private static final int ATTEMPT_TIMEOUT_MS = 50;
private final String[] ipsToTry;
private int lastTriedIndex = -1;
public NetworkScanner() {
ipsToTry = getIPsToTry();
}
/** Scan the next ip address in the list of addresses to try
*
* @return the hostname (or an ip represented as String) when a Hyperion server was found
*/
@Nullable
@WorkerThread
public String tryNext(){
if (!hasNextAttempt()){
throw new IllegalStateException("No more ip addresses to try");
}
Socket socket = new Socket();
String ip = ipsToTry[++lastTriedIndex];
try {
socket.connect(new InetSocketAddress(ip, PORT), ATTEMPT_TIMEOUT_MS);
if (socket.isConnected()){
socket.close();
return ip;
}
} catch(Exception e) {
return null;
}
return null;
}
/** An indication of how many of the total ip's have been tried
*
* @return progress in in the range [0.0 .. 1.0]
*/
public float getProgress() {
if (ipsToTry.length == 0){
return 1f;
}
return lastTriedIndex / (float)ipsToTry.length;
}
/** True if not all ip's have been tried yet
*
*/
public boolean hasNextAttempt(){
return ipsToTry.length > 0 && lastTriedIndex + 1 < ipsToTry.length;
}
/**
* Get IP addresses for non-localhost interfaces
* @param useIPv4 true=return ipv4, false=return ipv6
* @return a list of found addresses (may be empty)
*
* https://stackoverflow.com/a/13007325
*/
@NonNull
private static List<String> getIPAddresses(boolean useIPv4) {
List<String> foundAddresses = new ArrayList<>();
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress();
//boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
boolean isIPv4 = sAddr.indexOf(':')<0;
if (useIPv4) {
if (isIPv4)
foundAddresses.add(sAddr);
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
String v6Addr = delim < 0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
foundAddresses.add(v6Addr);
}
}
}
}
}
} catch (Exception e) {
// for now eat exceptions
Log.e("HYPERION SCANNER", "Could not get ip address", e);
}
return foundAddresses;
}
private String[] getIPsToTry(){
try {
List<String> localIpV4Addresses = getIPAddresses(true);
String[] allIpsToTry = new String[localIpV4Addresses.size() * 254];
for (int localIpIdx = 0; localIpIdx < localIpV4Addresses.size(); localIpIdx++) {
String localIpV4Address = localIpV4Addresses.get(localIpIdx);
String[] ipsToTry = new String[254];
String[] ipParts = localIpV4Address.split("\\.");
String ipPrefix = ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + ".";
for (int i = 1; i< 255 ; i++){
ipsToTry[i-1] = ipPrefix + i;
}
int localNumberInSubnet = Integer.parseInt(ipParts[3]);
// sort in such a way that ips close to the local ip will be tried first
Arrays.sort(ipsToTry, (lhs, rhs) -> {
int lhsNumberInSubnet = Integer.parseInt(lhs.split("\\.")[3]);
int rhsNumberInSubnet = Integer.parseInt(rhs.split("\\.")[3]);
int lhsDistance = Math.abs(lhsNumberInSubnet - localNumberInSubnet);
int rhsDistance = Math.abs(rhsNumberInSubnet - localNumberInSubnet);
return lhsDistance - rhsDistance;
});
for (int i = 0; i < ipsToTry.length; i++) {
// interleave with previously found ip addresses
int allIndex = (localIpV4Addresses.size() * i) + localIpIdx;
allIpsToTry[allIndex] = ipsToTry[i];
}
}
return allIpsToTry;
} catch (Exception e){
// for now eat exceptions
Log.e("HYPERION SCANNER", "Error while building list of subnet ip's", e);
return new String[]{};
}
}
}
@@ -0,0 +1,136 @@
package com.hyperion.grabber.common.network
import android.util.Log
import androidx.annotation.WorkerThread
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.NetworkInterface
import java.net.Socket
import java.util.Collections
import kotlin.math.abs
/** Scans the local network for running Hyperion servers */
class NetworkScanner {
private val ipsToTry: Array<String>
private var lastTriedIndex = -1
init {
ipsToTry = getIPsToTry()
}
/** Scan the next ip address in the list of addresses to try
* @return the hostname (or an ip represented as String) when a Hyperion server was found
*/
@WorkerThread
fun tryNext(): String? {
check(hasNextAttempt()) { "No more ip addresses to try" }
val socket = Socket()
val ip = ipsToTry[++lastTriedIndex]
try {
socket.connect(InetSocketAddress(ip, PORT), ATTEMPT_TIMEOUT_MS)
if (socket.isConnected) {
socket.close()
return ip
}
} catch (e: Exception) {
return null
}
return null
}
/** An indication of how many of the total ip's have been tried
* @return progress in in the range [0.0 .. 1.0]
*/
val progress: Float
get() {
if (ipsToTry.isEmpty()) {
return 1f
}
return lastTriedIndex / ipsToTry.size.toFloat()
}
/** True if not all ip's have been tried yet */
fun hasNextAttempt(): Boolean {
return ipsToTry.isNotEmpty() && lastTriedIndex + 1 < ipsToTry.size
}
private fun getIPsToTry(): Array<String> {
try {
val localIpV4Addresses = getIPAddresses(true)
val allIpsToTry = arrayOfNulls<String>(localIpV4Addresses.size * 254)
for (localIpIdx in localIpV4Addresses.indices) {
val localIpV4Address = localIpV4Addresses[localIpIdx]
val ipsToTry = arrayOfNulls<String>(254)
val ipParts = localIpV4Address.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val ipPrefix = ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + "."
for (i in 1..254) {
ipsToTry[i - 1] = ipPrefix + i
}
val localNumberInSubnet = ipParts[3].toInt()
// sort in such a way that ips close to the local ip will be tried first
ipsToTry.sortWith { lhs, rhs ->
val lhsNumberInSubnet = lhs!!.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[3].toInt()
val rhsNumberInSubnet = rhs!!.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[3].toInt()
val lhsDistance = abs(lhsNumberInSubnet - localNumberInSubnet)
val rhsDistance = abs(rhsNumberInSubnet - localNumberInSubnet)
lhsDistance - rhsDistance
}
for (i in ipsToTry.indices) {
// interleave with previously found ip addresses
val allIndex = localIpV4Addresses.size * i + localIpIdx
allIpsToTry[allIndex] = ipsToTry[i]
}
}
@Suppress("UNCHECKED_CAST")
return allIpsToTry as Array<String>
} catch (e: Exception) {
Log.e("HYPERION SCANNER", "Error while building list of subnet ip's", e)
return arrayOf()
}
}
companion object {
const val PORT = 19400
private const val ATTEMPT_TIMEOUT_MS = 50
/**
* Get IP addresses for non-localhost interfaces
* @param useIPv4 true=return ipv4, false=return ipv6
* @return a list of found addresses (may be empty)
*/
private fun getIPAddresses(useIPv4: Boolean): List<String> {
val foundAddresses: MutableList<String> = ArrayList()
try {
val interfaces = Collections.list(NetworkInterface.getNetworkInterfaces())
for (intf in interfaces) {
val addrs = Collections.list(intf.inetAddresses)
for (addr in addrs) {
if (!addr.isLoopbackAddress) {
val sAddr = addr.hostAddress ?: continue
val isIPv4 = sAddr.indexOf(':') < 0
if (useIPv4) {
if (isIPv4) foundAddresses.add(sAddr)
} else {
if (!isIPv4) {
val delim = sAddr.indexOf('%') // drop ip6 zone suffix
val v6Addr = if (delim < 0) sAddr.uppercase() else sAddr.substring(0, delim).uppercase()
foundAddresses.add(v6Addr)
}
}
}
}
}
} catch (e: Exception) {
Log.e("HYPERION SCANNER", "Could not get ip address", e)
}
return foundAddresses
}
}
}
@@ -0,0 +1,100 @@
package com.hyperion.grabber.common.network
import java.io.IOException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import kotlin.math.min
class WledDdpClient(
private val address: InetAddress,
private val port: Int = 4048
) : HyperionClient {
private var socket: DatagramSocket? = null
private var sequenceNumber = 1
override fun isConnected(): Boolean {
return socket?.isClosed == false
}
@Throws(IOException::class)
override fun disconnect() {
socket?.close()
socket = null
}
@Throws(IOException::class)
override fun clear(priority: Int) {
// DDP does not have a native 'clear' notion in this context, send black.
}
@Throws(IOException::class)
override fun clearAll() {
// Send black.
}
@Throws(IOException::class)
override fun setColor(color: Int, priority: Int) {
// Placeholder
}
@Throws(IOException::class)
override fun setColor(color: Int, priority: Int, duration_ms: Int) {
// Placeholder
}
@Throws(IOException::class)
override fun setImage(data: ByteArray, width: Int, height: Int, priority: Int) {
setImage(data, width, height, priority, -1)
}
@Throws(IOException::class)
override fun setImage(data: ByteArray, width: Int, height: Int, priority: Int, duration_ms: Int) {
if (socket == null || socket?.isClosed == true) {
socket = DatagramSocket()
}
// Each DDP packet can hold up to 1440 bytes of pixel data
val maxDataLen = 1440
var offset = 0
val totalLength = data.size
while (offset < totalLength) {
val chunkLen = min(maxDataLen, totalLength - offset)
val isFinalPacket = (offset + chunkLen) == totalLength
// Flags: 1 = ver1. 0x40 = PUSH. PUSH is only set on the final packet.
val flags = if (isFinalPacket) 0x41.toByte() else 0x01.toByte()
val packet = ByteArray(10 + chunkLen)
// DDP Header
packet[0] = flags // Flags
packet[1] = sequenceNumber.toByte() // Sequence
packet[2] = 1.toByte() // Data type: 1 = RGB, 0 = undefined
packet[3] = 1.toByte() // Destination: 1 = default
// Data offset (32-bit big-endian)
packet[4] = (offset ushr 24).toByte()
packet[5] = (offset ushr 16).toByte()
packet[6] = (offset ushr 8).toByte()
packet[7] = offset.toByte()
// Data length (16-bit big-endian)
packet[8] = (chunkLen ushr 8).toByte()
packet[9] = chunkLen.toByte()
// Copy data chunk
System.arraycopy(data, offset, packet, 10, chunkLen)
val datagram = DatagramPacket(packet, packet.size, address, port)
socket?.send(datagram)
offset += chunkLen
}
sequenceNumber = (sequenceNumber + 1) and 0x0F
if (sequenceNumber == 0) sequenceNumber = 1
}
}
@@ -0,0 +1,150 @@
package com.hyperion.grabber.common.util;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PermissionHelper {
private static final String TAG = "PermissionHelper";
public static boolean canDrawOverlays(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return Settings.canDrawOverlays(context);
}
return true;
}
public static void requestOverlayPermission(Activity activity, int requestCode) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(activity)) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + activity.getPackageName()));
activity.startActivityForResult(intent, requestCode);
} catch (Exception e) {
Log.e(TAG, "Cannot request overlay permission", e);
openAppSettings(activity);
}
}
}
public static boolean isIgnoringBatteryOptimizations(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
return pm != null && pm.isIgnoringBatteryOptimizations(context.getPackageName());
}
return true;
}
public static void requestIgnoreBatteryOptimizations(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + activity.getPackageName()));
activity.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "Cannot request battery optimization exemption", e);
}
}
}
public static boolean hasProjectMediaPermission(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
int mode = appOps.checkOpNoThrow("android:project_media",
android.os.Process.myUid(), context.getPackageName());
return mode == AppOpsManager.MODE_ALLOWED;
} catch (Exception e) {
Log.w(TAG, "Cannot check PROJECT_MEDIA permission", e);
}
}
return true;
}
public static void openAppSettings(Context context) {
try {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + context.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "Cannot open app settings", e);
Toast.makeText(context, "Please open Settings > Apps > Hyperion Grabber manually", Toast.LENGTH_LONG).show();
}
}
public static void tryGrantProjectMediaViaShell(Context context) {
new Thread(() -> {
try {
String pkg = context.getPackageName();
String[] commands = {
"appops set " + pkg + " PROJECT_MEDIA allow",
"appops set " + pkg + " android:project_media allow",
"appops set " + pkg + " SYSTEM_ALERT_WINDOW allow",
"pm grant " + pkg + " android.permission.SYSTEM_ALERT_WINDOW"
};
for (String cmd : commands) {
try {
Process process = Runtime.getRuntime().exec(new String[]{"sh", "-c", cmd});
process.waitFor();
Log.d(TAG, "Executed: " + cmd + " (exit: " + process.exitValue() + ")");
} catch (Exception e) {
Log.w(TAG, "Command failed: " + cmd);
}
}
} catch (Exception e) {
Log.e(TAG, "Shell commands failed", e);
}
}).start();
}
public static void showFullPermissionDialog(Activity activity, Runnable onRetry) {
String deviceInfo = "Device: " + Build.MANUFACTURER + " " + Build.MODEL;
String message = "Screen recording permission could not be obtained.\n\n" +
"Your TV may be blocking the permission dialog.\n\n" +
"SOLUTIONS:\n\n" +
"1. OVERLAY PERMISSION:\n" +
" Settings > Apps > Special access > Display over other apps\n\n" +
"2. APP PERMISSIONS:\n" +
" Settings > Apps > Hyperion Grabber > Permissions\n\n" +
"3. AUTO-START (TCL/Smart TVs):\n" +
" Settings > Privacy > Special app access > Auto-start\n" +
" OR Settings > Apps > App management\n\n" +
"4. BATTERY OPTIMIZATION:\n" +
" Settings > Apps > Special access > Battery optimization\n\n" +
"5. ADB COMMAND (requires computer):\n" +
" adb shell appops set " + activity.getPackageName() + " PROJECT_MEDIA allow\n\n" +
deviceInfo;
new AlertDialog.Builder(activity)
.setTitle("Permission Required")
.setMessage(message)
.setPositiveButton("Open App Settings", (d, w) -> openAppSettings(activity))
.setNeutralButton("Try Overlay", (d, w) -> {
requestOverlayPermission(activity, 999);
})
.setNegativeButton("Retry", (d, w) -> {
tryGrantProjectMediaViaShell(activity);
if (onRetry != null) {
activity.getWindow().getDecorView().postDelayed(() -> {
onRetry.run();
}, 1000);
}
})
.setCancelable(true)
.show();
}
}
@@ -0,0 +1,148 @@
package com.hyperion.grabber.common.util
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import org.json.JSONArray
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
data class GithubRelease(
val tagName: String,
val name: String,
val body: String,
val downloadUrl: String,
val publishedAt: String
)
class UpdateChecker(private val context: Context) {
private val TAG = "UpdateChecker"
private val GITHUB_API_URL = "https://api.github.com/repos/haumlab/hyperion-android-reborn/releases"
private val GITHUB_RELEASES_URL = "https://github.com/haumlab/hyperion-android-reborn/releases"
fun checkForUpdates(): GithubRelease? {
try {
val currentVersion = getCurrentVersion()
val latestRelease = fetchLatestRelease() ?: return null
Log.d(TAG, "Current version: $currentVersion, Latest version: ${latestRelease.tagName}")
if (isNewerVersion(latestRelease.tagName, currentVersion)) {
return latestRelease
}
} catch (e: Exception) {
Log.e(TAG, "Error checking for updates", e)
}
return null
}
private fun getCurrentVersion(): String {
return try {
val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.packageManager.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(0))
} else {
@Suppress("DEPRECATION")
context.packageManager.getPackageInfo(context.packageName, 0)
}
packageInfo.versionName ?: "0.0"
} catch (e: Exception) {
Log.e(TAG, "Error getting current version", e)
"0.0"
}
}
private fun fetchLatestRelease(): GithubRelease? {
var connection: HttpURLConnection? = null
try {
val url = URL(GITHUB_API_URL)
connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.setRequestProperty("Accept", "application/vnd.github.v3+json")
connection.connectTimeout = 10000
connection.readTimeout = 10000
val responseCode = connection.responseCode
if (responseCode != HttpURLConnection.HTTP_OK) {
Log.e(TAG, "GitHub API returned code: $responseCode")
return null
}
val reader = BufferedReader(InputStreamReader(connection.inputStream))
val response = reader.readText()
reader.close()
return parseReleases(response)
} catch (e: Exception) {
Log.e(TAG, "Error fetching releases", e)
return null
} finally {
connection?.disconnect()
}
}
private fun parseReleases(json: String): GithubRelease? {
try {
val releases = JSONArray(json)
// Find the first non-prerelease, non-draft release
for (i in 0 until releases.length()) {
val release = releases.getJSONObject(i)
val isDraft = release.optBoolean("draft", false)
val isPrerelease = release.optBoolean("prerelease", false)
if (!isDraft && !isPrerelease) {
val tagName = release.getString("tag_name")
val name = release.optString("name", tagName)
val body = release.optString("body", "")
val publishedAt = release.optString("published_at", "")
// Find APK asset
val assets = release.optJSONArray("assets")
var downloadUrl = ""
if (assets != null) {
for (j in 0 until assets.length()) {
val asset = assets.getJSONObject(j)
val assetName = asset.getString("name")
if (assetName.endsWith(".apk")) {
downloadUrl = asset.getString("browser_download_url")
break
}
}
}
if (downloadUrl.isEmpty()) {
Log.w(TAG, "No APK found for release $tagName")
continue
}
return GithubRelease(tagName, name, body, downloadUrl, publishedAt)
}
}
} catch (e: Exception) {
Log.e(TAG, "Error parsing releases", e)
}
return null
}
private fun isNewerVersion(newVersion: String, currentVersion: String): Boolean {
try {
val newParts = newVersion.removePrefix("v").split(".")
val currentParts = currentVersion.removePrefix("v").split(".")
for (i in 0 until maxOf(newParts.size, currentParts.size)) {
val newPart = newParts.getOrNull(i)?.toIntOrNull() ?: 0
val currentPart = currentParts.getOrNull(i)?.toIntOrNull() ?: 0
if (newPart > currentPart) return true
if (newPart < currentPart) return false
}
} catch (e: Exception) {
Log.e(TAG, "Error comparing versions", e)
}
return false
}
}
@@ -0,0 +1,157 @@
package com.hyperion.grabber.common.util
import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.core.content.FileProvider
import java.io.File
class UpdateManager(private val context: Context) {
private val TAG = "UpdateManager"
private var downloadId: Long = -1
private var downloadReceiver: BroadcastReceiver? = null
private val handler = Handler(Looper.getMainLooper())
fun downloadAndInstall(downloadUrl: String, versionName: String, onComplete: (Boolean) -> Unit) {
try {
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val fileName = "hyperion-grabber-${versionName.replace("v", "")}.apk"
val destinationFile = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName
)
if (destinationFile.exists()) {
destinationFile.delete()
}
val uri = Uri.parse(downloadUrl)
val request = DownloadManager.Request(uri).apply {
setTitle("Hyperion Grabber Update")
setDescription("Downloading $versionName")
setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
setMimeType("application/vnd.android.package-archive")
setAllowedOverMetered(true)
setAllowedOverRoaming(true)
}
downloadId = downloadManager.enqueue(request)
Log.d(TAG, "Download started: $downloadId from $downloadUrl")
showToast("Downloading update...")
downloadReceiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) {
val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) ?: -1
if (id == downloadId) {
Log.d(TAG, "Download complete: $id")
unregisterReceiver()
val query = DownloadManager.Query().setFilterById(downloadId)
val cursor = downloadManager.query(query)
if (cursor.moveToFirst()) {
val statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
val status = cursor.getInt(statusIndex)
if (status == DownloadManager.STATUS_SUCCESSFUL) {
showToast("Download complete, installing...")
installApk(fileName)
onComplete(true)
} else {
Log.e(TAG, "Download failed with status: $status")
showToast("Download failed")
onComplete(false)
}
}
cursor.close()
}
}
}
val filter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.registerReceiver(downloadReceiver, filter, Context.RECEIVER_EXPORTED)
} else {
context.registerReceiver(downloadReceiver, filter)
}
} catch (e: Exception) {
Log.e(TAG, "Download error", e)
showToast("Download failed: ${e.message}")
onComplete(false)
}
}
private fun installApk(fileName: String) {
try {
val file = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName
)
if (!file.exists()) {
Log.e(TAG, "APK file not found: ${file.absolutePath}")
showToast("APK file not found")
return
}
val uri: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider",
file
)
} else {
Uri.fromFile(file)
}
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "application/vnd.android.package-archive")
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
}
context.startActivity(intent)
Log.d(TAG, "Install intent launched for: $uri")
} catch (e: Exception) {
Log.e(TAG, "Install error", e)
showToast("Install failed: ${e.message}")
}
}
private fun unregisterReceiver() {
try {
downloadReceiver?.let { context.unregisterReceiver(it) }
downloadReceiver = null
} catch (e: Exception) {
Log.w(TAG, "Receiver already unregistered")
}
}
private fun showToast(message: String) {
handler.post { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() }
}
fun cancelDownload() {
if (downloadId != -1L) {
try {
val dm = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
dm.remove(downloadId)
unregisterReceiver()
} catch (e: Exception) {
Log.e(TAG, "Cancel error", e)
}
}
}
}