Migrate to FlatBuffers and unify Mobile/TV modules
This commit is contained in:
commit
2a4ee357ce
133 files changed
+7284
No files matched your search
@@ -0,0 +1,51 @@
|
||||
package com.hyperion.grabber.common;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.media.projection.MediaProjectionManager;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
public class BootActivity extends AppCompatActivity {
|
||||
public static final int REQUEST_MEDIA_PROJECTION = 1;
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
|
||||
@Override
|
||||
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
MediaProjectionManager manager = (MediaProjectionManager)
|
||||
getSystemService(Context.MEDIA_PROJECTION_SERVICE);
|
||||
if (manager != null) {
|
||||
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
|
||||
} else {
|
||||
finish();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
if (requestCode == REQUEST_MEDIA_PROJECTION) {
|
||||
if (resultCode == Activity.RESULT_OK) {
|
||||
startScreenRecorder(this, resultCode, data);
|
||||
}
|
||||
finish();
|
||||
}
|
||||
}
|
||||
|
||||
public static void startScreenRecorder(Context context, int resultCode, Intent data) {
|
||||
Intent intent = new Intent(context, HyperionScreenService.class);
|
||||
intent.setAction(HyperionScreenService.ACTION_START);
|
||||
intent.putExtra(HyperionScreenService.EXTRA_RESULT_CODE, resultCode);
|
||||
intent.putExtras(data);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
context.startForegroundService(intent);
|
||||
} else {
|
||||
context.startService(intent);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.hyperion.grabber.common;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
import androidx.annotation.RequiresApi;
|
||||
|
||||
import com.hyperion.grabber.common.util.Preferences;
|
||||
|
||||
public class HyperionGrabberBootReceiver extends BroadcastReceiver {
|
||||
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
|
||||
Preferences preferences = new Preferences(context);
|
||||
if (preferences.getBoolean(R.string.pref_key_boot)) {
|
||||
final Intent i = new Intent(context, BootActivity.class);
|
||||
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION
|
||||
|Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
|
||||
|Intent.FLAG_ACTIVITY_NO_HISTORY
|
||||
|Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
|
||||
context.startActivity(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.hyperion.grabber.common;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationChannel;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.PendingIntent;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.graphics.drawable.Icon;
|
||||
import android.os.Build;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.core.app.NotificationCompat;
|
||||
|
||||
public class HyperionNotification {
|
||||
private final String NOTIFICATION_CHANNEL_ID = "com.hyperion.grabber.notification";
|
||||
private final String NOTIFICATION_CHANNEL_LABEL;
|
||||
private final String NOTIFICATION_TITLE;
|
||||
private final String NOTIFICATION_DESCRIPTION;
|
||||
private final int PENDING_INTENT_REQUEST_CODE = 0;
|
||||
private final NotificationManager mNotificationManager;
|
||||
private final Context mContext;
|
||||
private Notification.Action mAction = null;
|
||||
|
||||
HyperionNotification (Context ctx, NotificationManager manager) {
|
||||
mNotificationManager = manager;
|
||||
mContext = ctx;
|
||||
NOTIFICATION_TITLE = mContext.getString(R.string.app_name);
|
||||
NOTIFICATION_DESCRIPTION = mContext.getString(R.string.notification_description);
|
||||
NOTIFICATION_CHANNEL_LABEL = mContext.getString(R.string.notification_channel_label);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
mNotificationManager.createNotificationChannel(makeChannel());
|
||||
}
|
||||
}
|
||||
|
||||
private int getPendingIntentFlags() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
return PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
|
||||
} else {
|
||||
return PendingIntent.FLAG_UPDATE_CURRENT;
|
||||
}
|
||||
}
|
||||
|
||||
public void setAction(int code, String label, Intent intent) {
|
||||
PendingIntent pendingIntent = PendingIntent.getService(mContext, code,
|
||||
intent, getPendingIntentFlags());
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
mAction = new Notification.Action.Builder(
|
||||
Icon.createWithResource(mContext, R.drawable.ic_notification_icon),
|
||||
label,
|
||||
pendingIntent
|
||||
).build();
|
||||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
|
||||
mAction = new Notification.Action.Builder(
|
||||
R.drawable.ic_notification_icon,
|
||||
label,
|
||||
pendingIntent
|
||||
).build();
|
||||
}
|
||||
}
|
||||
|
||||
public Notification buildNotification() {
|
||||
PendingIntent pIntent = null;
|
||||
Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());
|
||||
if (intent != null) {
|
||||
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
|
||||
pIntent = PendingIntent.getActivity(mContext, PENDING_INTENT_REQUEST_CODE,
|
||||
intent, getPendingIntentFlags());
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
Notification.Builder builder = new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
|
||||
.setOngoing(true)
|
||||
.setSmallIcon(R.drawable.ic_notification_icon)
|
||||
.setContentTitle(NOTIFICATION_TITLE)
|
||||
.setContentText(NOTIFICATION_DESCRIPTION);
|
||||
if (mAction != null) {
|
||||
builder.addAction(mAction);
|
||||
}
|
||||
if (pIntent != null) {
|
||||
builder.setContentIntent(pIntent);
|
||||
}
|
||||
return builder.build();
|
||||
} else {
|
||||
NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
|
||||
.setVibrate(null)
|
||||
.setSound(null)
|
||||
.setOngoing(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_MAX)
|
||||
.setSmallIcon(R.drawable.ic_notification_icon)
|
||||
.setContentTitle(NOTIFICATION_TITLE)
|
||||
.setContentText(NOTIFICATION_DESCRIPTION);
|
||||
if (pIntent != null) {
|
||||
builder.setContentIntent(pIntent);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.O)
|
||||
private NotificationChannel makeChannel() {
|
||||
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
|
||||
NOTIFICATION_CHANNEL_LABEL, NotificationManager.IMPORTANCE_DEFAULT);
|
||||
notificationChannel.setDescription(NOTIFICATION_CHANNEL_LABEL);
|
||||
notificationChannel.enableVibration(false);
|
||||
notificationChannel.setSound(null,null);
|
||||
return notificationChannel;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
package com.hyperion.grabber.common;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.graphics.PixelFormat;
|
||||
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.projection.MediaProjection;
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.HandlerThread;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import android.util.Log;
|
||||
|
||||
import com.hyperion.grabber.common.network.HyperionThread;
|
||||
import com.hyperion.grabber.common.util.BorderProcessor;
|
||||
import com.hyperion.grabber.common.util.HyperionGrabberOptions;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
public 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;
|
||||
|
||||
private VirtualDisplay mVirtualDisplay;
|
||||
private ImageReader mImageReader;
|
||||
private HandlerThread mCaptureThread;
|
||||
private Handler mCaptureHandler;
|
||||
private volatile boolean mRunning = false;
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
try {
|
||||
prepare();
|
||||
} catch (MediaCodec.CodecException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@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);
|
||||
mCaptureThread.start();
|
||||
mCaptureHandler = new Handler(mCaptureThread.getLooper());
|
||||
|
||||
int displayFlags = DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC;
|
||||
|
||||
mImageReader = ImageReader.newInstance(
|
||||
mCaptureWidth,
|
||||
mCaptureHeight,
|
||||
PixelFormat.RGBA_8888,
|
||||
MAX_IMAGE_READER_IMAGES
|
||||
);
|
||||
|
||||
mVirtualDisplay = mMediaProjection.createVirtualDisplay(
|
||||
TAG,
|
||||
mCaptureWidth, mCaptureHeight, mDensity,
|
||||
displayFlags,
|
||||
mImageReader.getSurface(),
|
||||
mDisplayCallback,
|
||||
mHandler);
|
||||
|
||||
startCaptureLoop();
|
||||
}
|
||||
|
||||
private void startCaptureLoop() {
|
||||
mRunning = true;
|
||||
setCapturing(true);
|
||||
|
||||
final long frameIntervalNs = 1_000_000_000L / mFrameRate;
|
||||
|
||||
mCaptureHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (!mRunning || !isCapturing()) {
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopRecording() {
|
||||
if (DEBUG) Log.i(TAG, "stopRecording Called");
|
||||
mRunning = false;
|
||||
setCapturing(false);
|
||||
|
||||
if (mCaptureHandler != null) {
|
||||
mCaptureHandler.removeCallbacksAndMessages(null);
|
||||
}
|
||||
|
||||
if (mVirtualDisplay != null) {
|
||||
mVirtualDisplay.release();
|
||||
mVirtualDisplay = null;
|
||||
}
|
||||
|
||||
if (mCaptureThread != null) {
|
||||
mCaptureThread.quitSafely();
|
||||
mCaptureThread = null;
|
||||
mCaptureHandler = null;
|
||||
}
|
||||
|
||||
mHandler.getLooper().quit();
|
||||
clearAndDisconnect();
|
||||
|
||||
if (mImageReader != null) {
|
||||
mImageReader.close();
|
||||
mImageReader = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resumeRecording() {
|
||||
if (DEBUG) Log.i(TAG, "resumeRecording Called");
|
||||
if (!isCapturing() && mImageReader != null) {
|
||||
startCaptureLoop();
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
|
||||
@Override
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.hyperion.grabber.common;
|
||||
|
||||
import android.content.res.Configuration;
|
||||
import android.media.projection.MediaProjection;
|
||||
import android.os.Handler;
|
||||
import android.os.HandlerThread;
|
||||
import android.os.Process;
|
||||
import android.util.Log;
|
||||
|
||||
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;
|
||||
private static final String TAG = "ScreenEncoderBase";
|
||||
private final int CLEAR_COMMAND_DELAY_MS = 100;
|
||||
private final int INIT_ORIENTATION;
|
||||
|
||||
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;
|
||||
|
||||
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");
|
||||
|
||||
mListener = listener;
|
||||
mMediaProjection = projection;
|
||||
mDensity = density;
|
||||
mFrameRate = options.getFrameRate();
|
||||
mAvgColor = options.useAverageColor();
|
||||
|
||||
int blackThreshold = options.getBlackThreshold();
|
||||
mBorderProcessor = new BorderProcessor(blackThreshold);
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
final HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_DISPLAY);
|
||||
thread.start();
|
||||
mHandler = new Handler(thread.getLooper());
|
||||
|
||||
if (DEBUG) Log.d(TAG, "Encoder ready");
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
void clearAndDisconnect() {
|
||||
new Thread(clearAndDisconnectRunner).start();
|
||||
}
|
||||
|
||||
public boolean isCapturing() {
|
||||
return mIsCapturing;
|
||||
}
|
||||
|
||||
public void setCapturing(boolean isCapturing) {
|
||||
mIsCapturing = isCapturing;
|
||||
}
|
||||
|
||||
public void sendStatus() {
|
||||
if (mListener != null) {
|
||||
mListener.sendStatus(isCapturing());
|
||||
}
|
||||
}
|
||||
|
||||
public void stopRecording() {
|
||||
throw new RuntimeException("Stub!");
|
||||
}
|
||||
|
||||
public void resumeRecording() {
|
||||
throw new RuntimeException("Stub!");
|
||||
}
|
||||
|
||||
int getGrabberWidth() {
|
||||
return INIT_ORIENTATION != mCurrentOrientation ? mHeightScaled : mWidthScaled;
|
||||
}
|
||||
|
||||
int getGrabberHeight() {
|
||||
return INIT_ORIENTATION != mCurrentOrientation ? mWidthScaled : mHeightScaled;
|
||||
}
|
||||
|
||||
public void setOrientation(int orientation) {
|
||||
mCurrentOrientation = orientation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package com.hyperion.grabber.common;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.Service;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.pm.ServiceInfo;
|
||||
import android.media.projection.MediaProjection;
|
||||
import android.media.projection.MediaProjectionManager;
|
||||
import android.os.Build;
|
||||
import android.os.IBinder;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.core.app.ServiceCompat;
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.util.Log;
|
||||
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 java.util.Objects;
|
||||
|
||||
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 String TAG = "HyperionScreenService";
|
||||
|
||||
private static final String BASE = "com.hyperion.grabber.service.";
|
||||
public static final String ACTION_START = BASE + "ACTION_START";
|
||||
public static final String ACTION_STOP = BASE + "ACTION_STOP";
|
||||
public static final String ACTION_EXIT = BASE + "ACTION_EXIT";
|
||||
public static final String GET_STATUS = BASE + "ACTION_STATUS";
|
||||
public static final String EXTRA_RESULT_CODE = BASE + "EXTRA_RESULT_CODE";
|
||||
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 MediaProjectionManager mMediaProjectionManager;
|
||||
private HyperionThread mHyperionThread;
|
||||
private static MediaProjection _mediaProjection;
|
||||
private int mFrameRate;
|
||||
private int mHorizontalLEDCount;
|
||||
private int mVerticalLEDCount;
|
||||
private boolean mSendAverageColor;
|
||||
private HyperionScreenEncoder mHyperionEncoder;
|
||||
private NotificationManager mNotificationManager;
|
||||
private String mStartError = null;
|
||||
|
||||
HyperionThreadBroadcaster mReceiver = new HyperionThreadBroadcaster() {
|
||||
@Override
|
||||
public void onConnected() {
|
||||
Log.d(TAG, "CONNECTED TO HYPERION INSTANCE");
|
||||
hasConnected = 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) {
|
||||
mStartError = getResources().getString(R.string.error_server_unreachable);
|
||||
haltStartup();
|
||||
}
|
||||
if (RECONNECT && hasConnected) {
|
||||
Log.e(TAG, "AUTOMATIC RECONNECT ENABLED. CONNECTING ...");
|
||||
} else if (!RECONNECT && hasConnected) {
|
||||
mStartError = getResources().getString(R.string.error_connection_lost);
|
||||
stopSelf();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onReceiveStatus(boolean isCapturing) {
|
||||
if (DEBUG) Log.v(TAG, "Received grabber status, notifying activity. Status: " +
|
||||
String.valueOf(isCapturing));
|
||||
notifyActivity();
|
||||
}
|
||||
};
|
||||
|
||||
BroadcastReceiver mEventReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
switch (Objects.requireNonNull(intent.getAction())) {
|
||||
case Intent.ACTION_SCREEN_ON:
|
||||
if (DEBUG) Log.v(TAG, "ACTION_SCREEN_ON intent received");
|
||||
if (mHyperionEncoder != null && !isCapturing()) {
|
||||
if (DEBUG) Log.v(TAG, "Encoder not grabbing, attempting to restart");
|
||||
mHyperionEncoder.resumeRecording();
|
||||
}
|
||||
notifyActivity();
|
||||
break;
|
||||
case Intent.ACTION_SCREEN_OFF:
|
||||
if (DEBUG) Log.v(TAG, "ACTION_SCREEN_OFF intent received");
|
||||
if (mHyperionEncoder != null) {
|
||||
if (DEBUG) Log.v(TAG, "Clearing current light data");
|
||||
mHyperionEncoder.clearLights();
|
||||
}
|
||||
break;
|
||||
case Intent.ACTION_CONFIGURATION_CHANGED:
|
||||
if (DEBUG) Log.v(TAG, "ACTION_CONFIGURATION_CHANGED intent received");
|
||||
if (mHyperionEncoder != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
if (DEBUG) Log.v(TAG, "Configuration changed, checking orientation");
|
||||
mHyperionEncoder.setOrientation(getResources().getConfiguration().orientation);
|
||||
}
|
||||
break;
|
||||
case Intent.ACTION_SHUTDOWN:
|
||||
case Intent.ACTION_REBOOT:
|
||||
if (DEBUG) Log.v(TAG, "ACTION_SHUTDOWN|ACTION_REBOOT intent received");
|
||||
stopScreenRecord();
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
|
||||
super.onCreate();
|
||||
}
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
|
||||
private boolean prepared() {
|
||||
Preferences prefs = new Preferences(getBaseContext());
|
||||
String host = prefs.getString(R.string.pref_key_host, null);
|
||||
int port = prefs.getInt(R.string.pref_key_port, -1);
|
||||
String priority = prefs.getString(R.string.pref_key_priority, "100");
|
||||
mFrameRate = prefs.getInt(R.string.pref_key_framerate);
|
||||
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);
|
||||
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 (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);
|
||||
mHyperionThread.start();
|
||||
mStartError = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
if (DEBUG) Log.v(TAG, "Start command received");
|
||||
super.onStartCommand(intent, flags, startId);
|
||||
if (intent == null || intent.getAction() == null) {
|
||||
String nullItem = (intent == null ? "intent" : "action");
|
||||
if (DEBUG) Log.v(TAG, "Null " + nullItem + " provided to start command");
|
||||
} else {
|
||||
final String action = intent.getAction();
|
||||
if (DEBUG) Log.v(TAG, "Start command action: " + String.valueOf(action));
|
||||
switch (action) {
|
||||
case ACTION_START:
|
||||
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());
|
||||
}
|
||||
|
||||
startScreenRecord(intent);
|
||||
|
||||
IntentFilter intentFilter = new IntentFilter();
|
||||
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
|
||||
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
|
||||
intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
|
||||
intentFilter.addAction(Intent.ACTION_REBOOT);
|
||||
intentFilter.addAction(Intent.ACTION_SHUTDOWN);
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
registerReceiver(mEventReceiver, intentFilter, Context.RECEIVER_NOT_EXPORTED);
|
||||
} else {
|
||||
registerReceiver(mEventReceiver, intentFilter);
|
||||
}
|
||||
} else {
|
||||
haltStartup();
|
||||
}
|
||||
}
|
||||
break;
|
||||
case ACTION_STOP:
|
||||
stopScreenRecord();
|
||||
break;
|
||||
case GET_STATUS:
|
||||
notifyActivity();
|
||||
break;
|
||||
case ACTION_EXIT:
|
||||
stopSelf();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return START_STICKY;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
if (DEBUG) Log.v(TAG, "Ending service");
|
||||
|
||||
try {
|
||||
unregisterReceiver(mEventReceiver);
|
||||
} catch (Exception e) {
|
||||
if (DEBUG) Log.v(TAG, "Wake receiver not registered");
|
||||
}
|
||||
|
||||
stopScreenRecord();
|
||||
stopForeground(true);
|
||||
notifyActivity();
|
||||
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
stopSelf();
|
||||
}
|
||||
|
||||
private Intent buildExitButton() {
|
||||
Intent notificationIntent = new Intent(this, this.getClass());
|
||||
notificationIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
|
||||
notificationIntent.setAction(ACTION_EXIT);
|
||||
return notificationIntent;
|
||||
}
|
||||
|
||||
public Notification getNotification() {
|
||||
HyperionNotification notification = new HyperionNotification(this, mNotificationManager);
|
||||
String label = getString(R.string.notification_exit_button);
|
||||
notification.setAction(NOTIFICATION_EXIT_INTENT_ID, label, buildExitButton());
|
||||
return notification.buildNotification();
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
private void startScreenRecord(final Intent intent) {
|
||||
if (DEBUG) Log.v(TAG, "Start 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;
|
||||
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);
|
||||
mHyperionEncoder.sendStatus();
|
||||
}
|
||||
}
|
||||
|
||||
private void stopScreenRecord() {
|
||||
if (DEBUG) Log.v(TAG, "Stop screen recorder");
|
||||
RECONNECT = false;
|
||||
mNotificationManager.cancel(NOTIFICATION_ID);
|
||||
if (mHyperionEncoder != null) {
|
||||
if (DEBUG) Log.v(TAG, "Stopping the current encoder");
|
||||
mHyperionEncoder.stopRecording();
|
||||
}
|
||||
releaseResource();
|
||||
if (mHyperionThread != null) {
|
||||
mHyperionThread.interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
public void releaseResource() {
|
||||
if (_mediaProjection != null) {
|
||||
_mediaProjection.stop();
|
||||
_mediaProjection = null;
|
||||
}
|
||||
}
|
||||
|
||||
boolean isCapturing() {
|
||||
return mHyperionEncoder != null && mHyperionEncoder.isCapturing();
|
||||
}
|
||||
|
||||
boolean isCommunicating() {
|
||||
return isCapturing() && hasConnected;
|
||||
}
|
||||
|
||||
private void notifyActivity() {
|
||||
Intent intent = new Intent(BROADCAST_FILTER);
|
||||
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);
|
||||
}
|
||||
}
|
||||
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
|
||||
}
|
||||
|
||||
public interface HyperionThreadBroadcaster {
|
||||
// void onResponse(String response);
|
||||
void onConnected();
|
||||
void onConnectionError(int errorHash, String errorString);
|
||||
void onReceiveStatus(boolean isCapturing);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.hyperion.grabber.common;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.ActivityManager;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.media.projection.MediaProjectionManager;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
public class ToggleActivity extends AppCompatActivity {
|
||||
public static final int REQUEST_MEDIA_PROJECTION = 1;
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
|
||||
@Override
|
||||
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
boolean serviceRunning = checkForInstance();
|
||||
|
||||
if (serviceRunning) {
|
||||
stopService();
|
||||
finish();
|
||||
} else {
|
||||
requestPermission();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||
super.onActivityResult(requestCode, resultCode, data);
|
||||
if (requestCode == REQUEST_MEDIA_PROJECTION) {
|
||||
if (resultCode == Activity.RESULT_OK) {
|
||||
startScreenRecorder(this, resultCode, data);
|
||||
}
|
||||
|
||||
finish();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private static void startScreenRecorder(Context context, int resultCode, Intent data) {
|
||||
Intent intent = new Intent(context, HyperionScreenService.class);
|
||||
intent.setAction(HyperionScreenService.ACTION_START);
|
||||
intent.putExtra(HyperionScreenService.EXTRA_RESULT_CODE, resultCode);
|
||||
intent.putExtras(data);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
context.startForegroundService(intent);
|
||||
} else {
|
||||
context.startService(intent);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return whether the service is running */
|
||||
private boolean checkForInstance() {
|
||||
if (isServiceRunning()) {
|
||||
Intent intent = new Intent(this, HyperionScreenService.class);
|
||||
intent.setAction(HyperionScreenService.GET_STATUS);
|
||||
startService(intent);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isServiceRunning() {
|
||||
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
|
||||
assert manager != null;
|
||||
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
|
||||
if (HyperionScreenService.class.getName().equals(service.service.getClassName())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
|
||||
private void requestPermission(){
|
||||
MediaProjectionManager manager = (MediaProjectionManager)
|
||||
getSystemService(Context.MEDIA_PROJECTION_SERVICE);
|
||||
if (manager != null) {
|
||||
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
|
||||
}
|
||||
}
|
||||
|
||||
/** stop recording & stop service */
|
||||
|
||||
private void stopService() {
|
||||
Intent stopIntent = new Intent(ToggleActivity.this, HyperionScreenService.class);
|
||||
stopIntent.setAction(HyperionScreenService.ACTION_EXIT);
|
||||
startService(stopIntent);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
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,137 @@
|
||||
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,124 @@
|
||||
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,171 @@
|
||||
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,186 @@
|
||||
package com.hyperion.grabber.common.util;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Objects;
|
||||
|
||||
public class BorderProcessor {
|
||||
|
||||
private final int MAX_INCONSISTENT_FRAME_COUNT = 10;
|
||||
private final int MAX_UNKNOWN_FRAME_COUNT = 600;
|
||||
private final int BORDER_CHANGE_FRAME_COUNT = 50;
|
||||
|
||||
private final int BLACK_THRESHOLD; // unit to detect how black a pixel is [0..255]
|
||||
private BorderObject mPreviousBorder;
|
||||
private BorderObject mCurrentBorder;
|
||||
private int mConsistentFrames = 0;
|
||||
private int mInconsistentFrames = 0;
|
||||
|
||||
public BorderProcessor(int blackThreshold) {
|
||||
BLACK_THRESHOLD = blackThreshold;
|
||||
}
|
||||
|
||||
public BorderObject getCurrentBorder() { return mCurrentBorder; }
|
||||
|
||||
private void checkNewBorder(BorderObject newBorder) {
|
||||
if (mPreviousBorder != null && mPreviousBorder.equals(newBorder)) {
|
||||
++mConsistentFrames;
|
||||
mInconsistentFrames = 0;
|
||||
} else {
|
||||
++mInconsistentFrames;
|
||||
|
||||
if (mInconsistentFrames <= MAX_INCONSISTENT_FRAME_COUNT) {
|
||||
return;
|
||||
}
|
||||
|
||||
mPreviousBorder = newBorder;
|
||||
mConsistentFrames = 0;
|
||||
}
|
||||
|
||||
if (mCurrentBorder != null && mCurrentBorder.equals(newBorder)) {
|
||||
mInconsistentFrames = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!newBorder.isKnown()) {
|
||||
if (mConsistentFrames == MAX_UNKNOWN_FRAME_COUNT) {
|
||||
mCurrentBorder = newBorder;
|
||||
}
|
||||
} else {
|
||||
if (mCurrentBorder == null || !mCurrentBorder.isKnown() ||
|
||||
mConsistentFrames == BORDER_CHANGE_FRAME_COUNT) {
|
||||
mCurrentBorder = newBorder;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void parseBorder(ByteBuffer buffer, int width, int height, int rowStride,
|
||||
int pixelStride) {
|
||||
checkNewBorder( findBorder(buffer, width, height, rowStride, pixelStride) );
|
||||
}
|
||||
|
||||
private BorderObject findBorder(ByteBuffer buffer, int width, int height, int rowStride,
|
||||
int pixelStride) {
|
||||
|
||||
int width33percent = width / 3;
|
||||
int width66percent = width33percent * 2;
|
||||
int height33percent = height / 3;
|
||||
int height66percent = height33percent * 2;
|
||||
int yCenter = height / 2;
|
||||
int xCenter = width / 2;
|
||||
int firstNonBlackYPixelIndex = -1;
|
||||
int firstNonBlackXPixelIndex = -1;
|
||||
|
||||
// placeholders for the RGB values of each of the 3 pixel positions we check
|
||||
int p1R, p1G, p1B, p2R, p2G, p2B, p3R, p3G, p3B;
|
||||
|
||||
// positions in the byte array that represent 33%, 66%, and center.
|
||||
// used when parsing both the X and Y axis of the image
|
||||
int pos33percent, pos66percent, posCentered;
|
||||
|
||||
buffer.position(0).mark();
|
||||
|
||||
// iterate through the X axis until we either hit 33% of the image width or a non-black pixel
|
||||
for (int x = 0; x < width33percent; x++) {
|
||||
|
||||
// RGB values at 33% height - to left of image
|
||||
pos33percent = (height33percent * rowStride) + (x * pixelStride);
|
||||
p1R = buffer.get(pos33percent) & 0xff;
|
||||
p1G = buffer.get(pos33percent + 1) & 0xff;
|
||||
p1B = buffer.get(pos33percent + 2) & 0xff;
|
||||
|
||||
// RGB values at 66% height - to left of image
|
||||
pos66percent = (height66percent * rowStride) + (x * pixelStride);
|
||||
p2R = buffer.get(pos66percent) & 0xff;
|
||||
p2G = buffer.get(pos66percent + 1) & 0xff;
|
||||
p2B = buffer.get(pos66percent + 2) & 0xff;
|
||||
|
||||
// RGB values at center Y - to right of image
|
||||
posCentered = (yCenter * rowStride) + ((width - x - 1) * pixelStride);
|
||||
p3R = buffer.get(posCentered) & 0xff;
|
||||
p3G = buffer.get(posCentered + 1) & 0xff;
|
||||
p3B = buffer.get(posCentered + 2) & 0xff;
|
||||
|
||||
// check if any of our RGB values DO NOT evaluate as black
|
||||
if (!isBlack(p1R,p1G,p1B) || !isBlack(p2R,p2G,p2B) || !isBlack(p3R,p3G,p3B)) {
|
||||
firstNonBlackXPixelIndex = x;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
buffer.reset();
|
||||
|
||||
// iterate through the Y axis until we either hit 33% of the image height or a non-black pixel
|
||||
for (int y = 0; y < height33percent; y++) {
|
||||
|
||||
// RGB values at 33% width - top of image
|
||||
pos33percent = (width33percent * pixelStride) + (y * rowStride);
|
||||
p1R = buffer.get(pos33percent) & 0xff;
|
||||
p1G = buffer.get(pos33percent + 1) & 0xff;
|
||||
p1B = buffer.get(pos33percent + 2) & 0xff;
|
||||
|
||||
// RGB values at 66% width - top of image
|
||||
pos66percent = (width66percent * pixelStride) + (y * rowStride);
|
||||
p2R = buffer.get(pos66percent) & 0xff;
|
||||
p2G = buffer.get(pos66percent + 1) & 0xff;
|
||||
p2B = buffer.get(pos66percent + 2) & 0xff;
|
||||
|
||||
// RGB values at center X - bottom of image
|
||||
posCentered = (xCenter * pixelStride) + ((height - y - 1) * rowStride);
|
||||
p3R = buffer.get(posCentered) & 0xff;
|
||||
p3G = buffer.get(posCentered + 1) & 0xff;
|
||||
p3B = buffer.get(posCentered + 2) & 0xff;
|
||||
|
||||
// check if any of our RGB values DO NOT evaluate as black
|
||||
if (!isBlack(p1R,p1G,p1B) || !isBlack(p2R,p2G,p2B) || !isBlack(p3R,p3G,p3B)) {
|
||||
firstNonBlackYPixelIndex = y;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new BorderObject(firstNonBlackXPixelIndex, firstNonBlackYPixelIndex);
|
||||
}
|
||||
|
||||
private boolean isBlack(int red, int green, int blue) {
|
||||
return red < BLACK_THRESHOLD && green < BLACK_THRESHOLD && blue < BLACK_THRESHOLD;
|
||||
}
|
||||
|
||||
public static class BorderObject {
|
||||
private boolean isKnown;
|
||||
private int horizontalBorderIndex;
|
||||
private int verticalBorderIndex;
|
||||
|
||||
BorderObject(int horizontalBorderIndex, int verticalBorderIndex) {
|
||||
this.horizontalBorderIndex = horizontalBorderIndex;
|
||||
this.verticalBorderIndex = verticalBorderIndex;
|
||||
this.isKnown = this.horizontalBorderIndex != -1 && this.verticalBorderIndex != -1;
|
||||
}
|
||||
|
||||
public boolean isKnown() { return isKnown; }
|
||||
public int getHorizontalBorderIndex() { return horizontalBorderIndex; }
|
||||
public int getVerticalBorderIndex() { return verticalBorderIndex; }
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
BorderObject that = (BorderObject) o;
|
||||
return isKnown == that.isKnown &&
|
||||
horizontalBorderIndex == that.horizontalBorderIndex &&
|
||||
verticalBorderIndex == that.verticalBorderIndex;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(isKnown, horizontalBorderIndex, verticalBorderIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "BorderObject{" +
|
||||
"isKnown=" + isKnown +
|
||||
", horizontalBorderIndex=" + horizontalBorderIndex +
|
||||
", verticalBorderIndex=" + verticalBorderIndex +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.hyperion.grabber.common.util;
|
||||
|
||||
import android.util.Log;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
public class HyperionGrabberOptions {
|
||||
private static final boolean DEBUG = false;
|
||||
private static final String TAG = "HyperionGrabberOptions";
|
||||
|
||||
private final int MINIMUM_IMAGE_PACKET_SIZE; // how many bytes the minimal acceptable image quality is
|
||||
private final int FRAME_RATE;
|
||||
private final boolean USE_AVERAGE_COLOR;
|
||||
private final int BLACK_THRESHOLD = 5; // The limit each RGB value must be under to be considered a black pixel [0-255]
|
||||
|
||||
public HyperionGrabberOptions(int horizontalLED, int verticalLED, int frameRate, boolean useAvgColor) {
|
||||
|
||||
/*
|
||||
* To determine the minimal acceptable image packet size we take the count of the width & height
|
||||
* of the LED pixels (that the user is driving via their hyperion server) and multiply them
|
||||
* together and then by 3 (1 for each color in RGB). This will give us the count of the bytes
|
||||
* that the minimal acceptable quality should be equal to or greater than.
|
||||
**/
|
||||
MINIMUM_IMAGE_PACKET_SIZE = horizontalLED * verticalLED * 3;
|
||||
FRAME_RATE = frameRate;
|
||||
USE_AVERAGE_COLOR = useAvgColor;
|
||||
|
||||
if (DEBUG) {
|
||||
Log.d(TAG, "Horizontal LED Count: " + String.valueOf(horizontalLED));
|
||||
Log.d(TAG, "Vertical LED Count: " + String.valueOf(verticalLED));
|
||||
Log.d(TAG, "Minimum Image Packet: " + String.valueOf(MINIMUM_IMAGE_PACKET_SIZE));
|
||||
}
|
||||
}
|
||||
|
||||
public int getFrameRate() { return FRAME_RATE; }
|
||||
|
||||
public boolean useAverageColor() { return USE_AVERAGE_COLOR; }
|
||||
|
||||
/**
|
||||
* returns the divisor best suited to be used to meet the minimum image packet size
|
||||
* Since we only want to scale using whole numbers, we need to find what common divisors
|
||||
* are available for the given width & height. We will check those divisors to find the smallest
|
||||
* number (that we can divide our screen dimensions by) that would meet the minimum image
|
||||
* packet size required to match the count of the LEDs on the destination hyperion server.
|
||||
* @param width The original width of the device screen
|
||||
* @param height The original height of the device screen
|
||||
* @return int The divisor bes suited to scale the screen dimensions by
|
||||
**/
|
||||
public int findDivisor(int width, int height) {
|
||||
List<Integer> divisors = getCommonDivisors(width, height);
|
||||
if (DEBUG) Log.d(TAG, "Available Divisors: " + divisors.toString());
|
||||
ListIterator it = divisors.listIterator(divisors.size());
|
||||
|
||||
// iterate backwards since the divisors are listed largest to smallest
|
||||
while (it.hasPrevious()) {
|
||||
int i = (int) it.previous();
|
||||
|
||||
// check if the image packet size for this divisor is >= the minimum image packet size
|
||||
// like above we multiply the dimensions together and then by 3 for each byte in RGB
|
||||
if ((width / i) * (height / i) * 3 >= MINIMUM_IMAGE_PACKET_SIZE)
|
||||
return i;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* gets a list of all the common divisors [large to small] for the given integers.
|
||||
* @param num1 The first integer to find a whole number divisor for
|
||||
* @param num2 The second integer to find a whole number divisor for
|
||||
* @return List A list of the common divisors [large to small] that match the provided integers
|
||||
**/
|
||||
private static List<Integer> getCommonDivisors(int num1, int num2) {
|
||||
List<Integer> list = new ArrayList<>();
|
||||
int min = Math.min(num1, num2);
|
||||
for (int i = 1; i <= min / 2; i++)
|
||||
if (num1 % i == 0 && num2 % i == 0)
|
||||
list.add(i);
|
||||
if (num1 % min == 0 && num2 % min == 0) list.add(min);
|
||||
return list;
|
||||
}
|
||||
|
||||
public int getBlackThreshold() { return BLACK_THRESHOLD; }
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.hyperion.grabber.common.util;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import androidx.annotation.Nullable;
|
||||
import android.util.Log;
|
||||
|
||||
import com.hyperion.grabber.common.network.NetworkScanner;
|
||||
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
|
||||
/**
|
||||
* Starts a network scan for a running Hyperion server
|
||||
* and posts progress and results
|
||||
*/
|
||||
public class HyperionScannerTask {
|
||||
private WeakReference<Listener> weakListener;
|
||||
private ExecutorService executor = Executors.newSingleThreadExecutor();
|
||||
private Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
|
||||
public HyperionScannerTask(Listener listener){
|
||||
weakListener = new WeakReference<>(listener);
|
||||
}
|
||||
|
||||
public void execute() {
|
||||
executor.execute(() -> {
|
||||
String result = doInBackground();
|
||||
mainHandler.post(() -> onPostExecute(result));
|
||||
});
|
||||
}
|
||||
|
||||
private String doInBackground() {
|
||||
Log.d("Hyperion scanner", "starting scan");
|
||||
NetworkScanner networkScanner = new NetworkScanner();
|
||||
|
||||
String result;
|
||||
while (networkScanner.hasNextAttempt()){
|
||||
result = networkScanner.tryNext();
|
||||
|
||||
if (result != null){
|
||||
return result;
|
||||
}
|
||||
|
||||
final float progress = networkScanner.getProgress();
|
||||
mainHandler.post(() -> onProgressUpdate(progress));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void onProgressUpdate(Float value) {
|
||||
Log.d("Hyperion scanner", "scan progress: " + value);
|
||||
if(weakListener.get() != null){
|
||||
weakListener.get().onScannerProgress(value);
|
||||
}
|
||||
}
|
||||
|
||||
private void onPostExecute(String result) {
|
||||
Log.d("Hyperion scanner", "scan result: " + result);
|
||||
if(weakListener.get() != null){
|
||||
weakListener.get().onScannerCompleted(result);
|
||||
}
|
||||
}
|
||||
|
||||
public interface Listener {
|
||||
|
||||
void onScannerProgress(float progress);
|
||||
void onScannerCompleted(@Nullable String foundIpAddress);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.hyperion.grabber.common.util
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.Resources
|
||||
import androidx.preference.PreferenceManager
|
||||
import androidx.annotation.StringRes
|
||||
|
||||
/** 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 */
|
||||
class Preferences(context: Context) {
|
||||
|
||||
private val preferences = PreferenceManager.getDefaultSharedPreferences(context)
|
||||
private val resources = context.resources
|
||||
|
||||
fun contains(@StringRes keyResourceId: Int): Boolean = preferences.contains(key(keyResourceId))
|
||||
|
||||
fun getString(@StringRes keyResourceId: Int, default: String? = null): String? {
|
||||
return preferences.getString(key(keyResourceId), default)
|
||||
}
|
||||
|
||||
fun putString(@StringRes keyResourceId: Int, value: String){
|
||||
val edit = preferences.edit()
|
||||
edit.putString(key(keyResourceId), value)
|
||||
edit.apply()
|
||||
}
|
||||
|
||||
fun getInt(@StringRes keyResourceId: Int): Int {
|
||||
val default = defaultKey(keyResourceId, "integer").let {
|
||||
if (it == 0){
|
||||
0
|
||||
} else {
|
||||
try {
|
||||
resources.getInteger(it)
|
||||
} catch (e: Resources.NotFoundException) {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return getInt(keyResourceId, default)
|
||||
}
|
||||
|
||||
fun getInt(@StringRes keyResourceId: Int, default: Int = 0): Int {
|
||||
return getString(keyResourceId)?.let { Integer.parseInt(it) } ?: default
|
||||
}
|
||||
|
||||
fun putInt(@StringRes keyResourceId: Int, value: Int){
|
||||
putString(keyResourceId, value.toString())
|
||||
}
|
||||
|
||||
fun getBoolean(@StringRes keyResourceId: Int): Boolean {
|
||||
val default = defaultKey(keyResourceId, "bool").let {
|
||||
if (it == 0){
|
||||
false
|
||||
} else {
|
||||
try {
|
||||
resources.getBoolean(it)
|
||||
} catch (e: Resources.NotFoundException) {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return preferences.getBoolean(key(keyResourceId), default)
|
||||
}
|
||||
|
||||
fun getBoolean(@StringRes keyResourceId: Int, default: Boolean): Boolean =
|
||||
preferences.getBoolean(key(keyResourceId), default)
|
||||
|
||||
fun putBoolean(@StringRes keyResourceId: Int, value: Boolean){
|
||||
val edit = preferences.edit()
|
||||
edit.putBoolean(key(keyResourceId), value)
|
||||
edit.apply()
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.hyperion.grabber.common.views;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Matrix;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.SweepGradient;
|
||||
import androidx.annotation.Nullable;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
|
||||
/**
|
||||
* Created by nino on 26-5-18.
|
||||
*/
|
||||
|
||||
public class SweepGradientView extends View{
|
||||
|
||||
Paint paint;
|
||||
final int[] colors = {Color.RED, Color.MAGENTA, Color.BLUE, Color.CYAN, Color.GREEN, Color.YELLOW, Color.RED};
|
||||
final float[] positions = {0f, 1/6f, 2/6f, 3/6f, 4/6f, 5/6f, 6/6f};
|
||||
|
||||
SweepGradient gradient;
|
||||
|
||||
Rect viewBounds = new Rect();
|
||||
|
||||
Matrix gradientMatrix = new Matrix();
|
||||
|
||||
float rotate = 0f;
|
||||
|
||||
public SweepGradientView(Context context) {
|
||||
this(context, null);
|
||||
}
|
||||
|
||||
public SweepGradientView(Context context, @Nullable AttributeSet attrs) {
|
||||
this(context, attrs, 0);
|
||||
}
|
||||
|
||||
public SweepGradientView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
|
||||
paint = new Paint();
|
||||
paint.setShader(gradient);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected void onDraw(Canvas canvas) {
|
||||
|
||||
gradientMatrix.postRotate(rotate++, viewBounds.width()/2, viewBounds.height()/2);
|
||||
gradient.setLocalMatrix(gradientMatrix);
|
||||
|
||||
paint.setShader(gradient);
|
||||
canvas.drawRect(viewBounds, paint);
|
||||
gradientMatrix.reset();
|
||||
invalidate();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
|
||||
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
|
||||
viewBounds.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
|
||||
|
||||
gradient = new SweepGradient(viewBounds.centerX(), viewBounds.centerY(), colors, positions);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user