package com.hyperion.grabber.common; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Rect; import android.hardware.display.DisplayManager; import android.hardware.display.VirtualDisplay; import android.media.Image; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import android.media.projection.MediaProjection; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import android.os.SystemClock; import android.util.Log; import android.view.Surface; import androidx.annotation.RequiresApi; import com.hyperion.grabber.common.network.HyperionThread; import com.hyperion.grabber.common.util.AnimationSyncController; import com.hyperion.grabber.common.util.AudioVisualizerController; import com.hyperion.grabber.common.util.HyperionGrabberOptions; import com.hyperion.grabber.common.util.Preferences; import java.nio.ByteBuffer; /** * Screen capture via MediaProjection → VirtualDisplay → MediaCodec encoder Surface * → MediaCodec decoder → YUV→RGB (scrcpy/recorder-like path). * * Avoids ImageReader as the MediaProjection consumer, which yields black frames on * some Amlogic SoCs (e.g. S905X5M / Ugoos X5M Pro). */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public final class HyperionScreenEncoder extends HyperionScreenEncoderBase { private static final String TAG = "HyperionScreenEncoder"; private static final boolean DEBUG = false; private static final String MIME_TYPE = MediaFormat.MIMETYPE_VIDEO_AVC; private static final int MAX_CAPTURE_WIDTH = 640; private static final int MIN_CAPTURE_SIDE = 160; private static final int MAX_OUTPUT_WIDTH = 128; private static final int MAX_OUTPUT_HEIGHT = 72; private static final int BYTES_PER_PIXEL_RGB = 3; private static final int RGB_BUFFER_RING_SIZE = 3; private static final int CODEC_TIMEOUT_US = 5_000; private static final long FPS_LOG_INTERVAL_MS = 5_000L; private static final int CONTENT_BOUNDS_LOCK_STABLE = 2; private static final int CONTENT_BOUNDS_HYSTERESIS_PX = 16; private static final int BLACK_Y_THRESHOLD = 32; /** ~1.5 Mbps — enough for LED colors, light on Amlogic. */ private static final int MIN_ENCODER_BITRATE = 1_500_000; private static final float LETTERBOX_FILL_MAX = 0.70f; private VirtualDisplay mVirtualDisplay; private MediaCodec mEncoder; private MediaCodec mDecoder; private Surface mEncoderSurface; private HandlerThread mCodecThread; private Handler mCodecHandler; private volatile boolean mRunning; private volatile boolean mDisplayPaused; private volatile boolean mDecoderConfigured; private int mCaptureWidth; private int mCaptureHeight; private int mOutputWidth; private int mOutputHeight; private int mScreenWidth; private int mScreenHeight; private final Rect mContentBounds = new Rect(); private final Rect mPendingBounds = new Rect(); private boolean mContentBoundsValid; private boolean mContentBoundsLocked; private int mBoundsFrameCounter; private int mStableBoundsCount; private byte[][] mRgbBufferRing = new byte[RGB_BUFFER_RING_SIZE][]; private int mRgbBufferIndex = 0; private final byte[] mAvgColorResult = new byte[3]; private final long mFrameIntervalMs; private long mLastFrameSentAtMs; private long mFpsWindowStartMs; private int mFpsWindowCount; private int mFramesSent; private int mBlackFrameCount; private volatile float mLastSendFps; private AnimationSyncController mAnimationSync; private Preferences mPreferences; private AudioVisualizerController mAudioVisualizer; private boolean mAudioOnlyMode = false; private boolean mAnimationAutoEnabled = false; private final MediaCodec.BufferInfo mEncoderInfo = new MediaCodec.BufferInfo(); private final MediaCodec.BufferInfo mDecoderInfo = new MediaCodec.BufferInfo(); private final Runnable mCodecPump = new Runnable() { @Override public void run() { if (!mRunning) return; try { if (mAudioOnlyMode && mAudioVisualizer != null) { generateAudioVisualization(); } else { // Keep draining even if VD reported pause — otherwise Home freezes LEDs // permanently. feedDecoder must never busy-loop (that froze the box on resume). drainEncoderFeedDecoder(); drainDecoderToRgb(); } } catch (Exception e) { Log.e(TAG, "Codec pump error: " + e.getMessage(), e); } if (mRunning && mCodecHandler != null) { // Never spin at 1ms — that froze the X5M. Pace to target FPS. mCodecHandler.postDelayed(this, Math.max(8L, mFrameIntervalMs)); } } }; private final VirtualDisplay.Callback mDisplayCallback = new VirtualDisplay.Callback() { @Override public void onPaused() { mDisplayPaused = true; Log.i(TAG, "VirtualDisplay paused (pump keeps running, no busy-wait)"); } @Override public void onResumed() { Log.i(TAG, "VirtualDisplay resumed"); mDisplayPaused = false; if (!mRunning) { startCapture(); } else if (mCodecHandler != null) { mCodecHandler.removeCallbacks(mCodecPump); mCodecHandler.post(mCodecPump); } } @Override public void onStopped() { Log.i(TAG, "VirtualDisplay stopped"); mRunning = false; mDisplayPaused = true; setCapturing(false); } }; HyperionScreenEncoder(HyperionThread.HyperionThreadListener listener, MediaProjection projection, int screenWidth, int screenHeight, int density, HyperionGrabberOptions options, Context context) { super(listener, projection, screenWidth, screenHeight, density, options); mFrameIntervalMs = 1000L / Math.max(1, mFrameRate); initDimensions(screenWidth, screenHeight); if (context != null) { mPreferences = new Preferences(context); int frameDelay = mPreferences.getInt(R.string.pref_key_frame_delay, 0); boolean enableAnimation = mPreferences.getBoolean(R.string.pref_key_enable_animation, false); mAudioOnlyMode = mPreferences.getBoolean(R.string.pref_key_audio_only_mode, false); mAnimationSync = new AnimationSyncController(frameDelay, enableAnimation); if (mAudioOnlyMode) { mAudioVisualizer = new AudioVisualizerController(); mAnimationAutoEnabled = true; } } else { mAnimationSync = new AnimationSyncController(0, false); } Log.i(TAG, "Pipeline=MediaCodec capture=" + mCaptureWidth + "x" + mCaptureHeight + " output=" + mOutputWidth + "x" + mOutputHeight + " fps=" + mFrameRate + " density=" + density); try { init(); } catch (Exception e) { Log.e(TAG, "MediaCodec pipeline init failed", e); releaseCodecResources(); } } private void initDimensions(int screenWidth, int screenHeight) { mScreenWidth = Math.max(1, screenWidth); mScreenHeight = Math.max(1, screenHeight); mOutputWidth = Math.max(4, Math.min(getGrabberWidth(), MAX_OUTPUT_WIDTH)) & ~1; mOutputHeight = Math.max(4, Math.min(getGrabberHeight(), MAX_OUTPUT_HEIGHT)) & ~1; // Keep capture small on Amlogic — 960x540 + encode/decode froze the box. float aspect = (float) mScreenWidth / (float) mScreenHeight; if (Math.abs(aspect - (16f / 9f)) < 0.05f) { mCaptureWidth = 640; mCaptureHeight = 360; } else { int capW = Math.min(MAX_CAPTURE_WIDTH, mScreenWidth) & ~1; int capH = Math.round(capW / aspect) & ~1; if (capH < MIN_CAPTURE_SIDE) { capH = MIN_CAPTURE_SIDE & ~1; capW = Math.round(capH * aspect) & ~1; } mCaptureWidth = Math.max(MIN_CAPTURE_SIDE, capW); mCaptureHeight = Math.max(MIN_CAPTURE_SIDE, capH); } Log.i(TAG, "Screen=" + mScreenWidth + "x" + mScreenHeight + " capture=" + mCaptureWidth + "x" + mCaptureHeight + " output=" + mOutputWidth + "x" + mOutputHeight); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private void init() throws Exception { mCodecThread = new HandlerThread(TAG + "-codec", android.os.Process.THREAD_PRIORITY_BACKGROUND); mCodecThread.start(); mCodecHandler = new Handler(mCodecThread.getLooper()); setupEncoder(); setupDecoder(); mMediaProjection.registerCallback(new MediaProjection.Callback() { @Override public void onStop() { Log.i(TAG, "MediaProjection stopped"); stopRecording(); } }, mHandler); int flags = DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR; Log.i(TAG, "Creating VirtualDisplay flags=AUTO_MIRROR surface=MediaCodecEncoder"); mVirtualDisplay = mMediaProjection.createVirtualDisplay( TAG, mCaptureWidth, mCaptureHeight, mDensity, flags, mEncoderSurface, mDisplayCallback, mHandler); if (mVirtualDisplay == null) { throw new IllegalStateException("createVirtualDisplay returned null"); } Log.i(TAG, "VirtualDisplay created OK"); startCapture(); } private void setupEncoder() throws Exception { MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mCaptureWidth, mCaptureHeight); format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); // Low-ish bitrate: LED ambilight does not need cinema quality; high bitrate froze X5M. final int bitrate = Math.max(MIN_ENCODER_BITRATE, mCaptureWidth * mCaptureHeight * 3); format.setInteger(MediaFormat.KEY_BIT_RATE, bitrate); format.setInteger(MediaFormat.KEY_FRAME_RATE, Math.min(30, Math.max(10, mFrameRate))); format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2); format.setInteger(MediaFormat.KEY_BITRATE_MODE, MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { format.setInteger(MediaFormat.KEY_LATENCY, 0); } Log.i(TAG, "Encoder format bitrate=" + bitrate + " : " + format); mEncoder = MediaCodec.createEncoderByType(MIME_TYPE); mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); mEncoderSurface = mEncoder.createInputSurface(); mEncoder.start(); Log.i(TAG, "Encoder started: " + mEncoder.getName()); } private void setupDecoder() throws Exception { MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, mCaptureWidth, mCaptureHeight); // ByteBuffer / Image mode — not ImageReader as MediaProjection consumer. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible); } Log.i(TAG, "Decoder format: " + format); mDecoder = MediaCodec.createDecoderByType(MIME_TYPE); mDecoder.configure(format, null, null, 0); mDecoder.start(); mDecoderConfigured = true; Log.i(TAG, "Decoder started: " + mDecoder.getName()); } private void startCapture() { mRunning = true; mDisplayPaused = false; setCapturing(true); mFpsWindowStartMs = SystemClock.elapsedRealtime(); mFpsWindowCount = 0; mFramesSent = 0; mBlackFrameCount = 0; mLastFrameSentAtMs = 0; // Keep letterbox lock across pause/resume — only reset on fresh pipeline init. if (!mContentBoundsLocked) { mContentBoundsValid = false; mBoundsFrameCounter = 0; mStableBoundsCount = 0; } if (mAudioOnlyMode && mAudioVisualizer != null) { mAudioVisualizer.start(); if (mAnimationSync != null && mAnimationAutoEnabled) { mAnimationSync.setAnimationEnabled(true); } } if (mCodecHandler != null) { mCodecHandler.removeCallbacks(mCodecPump); mCodecHandler.post(mCodecPump); } Log.i(TAG, "Capture started (MediaCodec path)"); } private void drainEncoderFeedDecoder() { if (mEncoder == null || mDecoder == null || !mDecoderConfigured) return; // Cap work per tick so a backlog cannot freeze the box. final int maxPackets = 8; for (int n = 0; n < maxPackets; n++) { int outIndex = mEncoder.dequeueOutputBuffer(mEncoderInfo, 0); if (outIndex == MediaCodec.INFO_TRY_AGAIN_LATER) { break; } else if (outIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { Log.i(TAG, "Encoder output format changed: " + mEncoder.getOutputFormat()); } else if (outIndex >= 0) { ByteBuffer encoded = mEncoder.getOutputBuffer(outIndex); boolean fed = false; if (encoded != null && mEncoderInfo.size > 0) { encoded.position(mEncoderInfo.offset); encoded.limit(mEncoderInfo.offset + mEncoderInfo.size); fed = feedDecoder(encoded, mEncoderInfo.size, mEncoderInfo.presentationTimeUs, mEncoderInfo.flags); } // Always release — never hold encoder buffers while spinning on decoder. mEncoder.releaseOutputBuffer(outIndex, false); if (!fed && mEncoderInfo.size > 0) { // Decoder was busy; free some output then continue next tick. drainDecoderToRgb(); break; } if ((mEncoderInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { break; } } else { break; } } } /** * @return true if the packet was queued; false if dropped (never busy-loops). */ private boolean feedDecoder(ByteBuffer data, int size, long ptsUs, int flags) { // Free decoder outputs first so input buffers become available. drainDecoderToRgb(); for (int attempt = 0; attempt < 3; attempt++) { if (!mRunning) return false; int inIndex = mDecoder.dequeueInputBuffer(0); if (inIndex >= 0) { ByteBuffer input = mDecoder.getInputBuffer(inIndex); if (input == null) return false; input.clear(); if (size > input.capacity()) { Log.w(TAG, "Encoded packet larger than decoder input, dropping"); return false; } input.put(data); mDecoder.queueInputBuffer(inIndex, 0, size, ptsUs, flags); return true; } if (inIndex != MediaCodec.INFO_TRY_AGAIN_LATER) { return false; } drainDecoderToRgb(); } return false; } private void drainDecoderToRgb() { if (mDecoder == null) return; long now = SystemClock.elapsedRealtime(); boolean throttle = (now - mLastFrameSentAtMs) < mFrameIntervalMs; final int maxFrames = 4; for (int n = 0; n < maxFrames; n++) { int outIndex = mDecoder.dequeueOutputBuffer(mDecoderInfo, 0); if (outIndex == MediaCodec.INFO_TRY_AGAIN_LATER) { break; } else if (outIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { Log.i(TAG, "Decoder output format: " + mDecoder.getOutputFormat()); } else if (outIndex >= 0) { boolean render = mDecoderInfo.size > 0 && !throttle; if (render) { Image image = null; try { image = mDecoder.getOutputImage(outIndex); if (image != null) { processDecodedImage(image); mLastFrameSentAtMs = now; throttle = true; } } catch (Exception e) { Log.w(TAG, "getOutputImage failed: " + e.getMessage()); } finally { if (image != null) { image.close(); } } } mDecoder.releaseOutputBuffer(outIndex, false); if ((mDecoderInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { break; } } else { break; } } } private void processDecodedImage(Image image) { final int outW = mOutputWidth; final int outH = mOutputHeight; byte[] rgb = getRgbBuffer(outW, outH); if (mAvgColor) { computeAverageColor(image, rgb); mListener.sendFrame(mAvgColorResult, 1, 1); } else { yuvToRgbDownscale(image, rgb, outW, outH); if (mAnimationSync != null) { rgb = mAnimationSync.applyAnimationToFrame(rgb); } logFrameStats(rgb, outW, outH); mListener.sendFrame(rgb, outW, outH); } mRgbBufferIndex = (mRgbBufferIndex + 1) % RGB_BUFFER_RING_SIZE; mFramesSent++; mFpsWindowCount++; maybeLogFps(); } private void logFrameStats(byte[] rgb, int width, int height) { int sample = Math.min(rgb.length, 300); int nonZero = 0; long sum = 0; for (int i = 0; i < sample; i++) { int v = rgb[i] & 0xFF; sum += v; if (v != 0) nonZero++; } boolean black = nonZero == 0; if (black) { mBlackFrameCount++; } if (DEBUG && (mFramesSent < 5 || mFramesSent % 60 == 0 || black)) { Log.i(TAG, "Frame#" + mFramesSent + " " + width + "x" + height + " nonZeroSample=" + nonZero + "/" + sample + " avgSample=" + (sample > 0 ? (sum / sample) : 0) + " blackFrames=" + mBlackFrameCount); } } private void maybeLogFps() { long now = SystemClock.elapsedRealtime(); long elapsed = now - mFpsWindowStartMs; if (elapsed >= FPS_LOG_INTERVAL_MS) { float fps = mFpsWindowCount * 1000f / elapsed; mLastSendFps = fps; if (DEBUG) { Log.i(TAG, "Send-FPS=" + String.format("%.1f", fps) + " framesSent=" + mFramesSent + " blackFrames=" + mBlackFrameCount + " capture=" + mCaptureWidth + "x" + mCaptureHeight + " output=" + mOutputWidth + "x" + mOutputHeight); } mFpsWindowStartMs = now; mFpsWindowCount = 0; } } public float getSendFps() { long elapsed = SystemClock.elapsedRealtime() - mFpsWindowStartMs; if (elapsed >= 500L && mFpsWindowCount > 0) { return mFpsWindowCount * 1000f / elapsed; } return mLastSendFps; } public int getFramesSent() { return mFramesSent; } public int getBlackFrameCount() { return mBlackFrameCount; } public int getCaptureWidth() { return mCaptureWidth; } public int getCaptureHeight() { return mCaptureHeight; } public int getOutputWidth() { return mOutputWidth; } public int getOutputHeight() { return mOutputHeight; } public int getTargetFrameRate() { return mFrameRate; } private void yuvToRgbDownscale(Image image, byte[] rgb, int outW, int outH) { final Image.Plane[] planes = image.getPlanes(); if (planes.length < 3) { Log.w(TAG, "Unexpected plane count: " + planes.length); return; } final ByteBuffer yBuf = planes[0].getBuffer(); final ByteBuffer uBuf = planes[1].getBuffer(); final ByteBuffer vBuf = planes[2].getBuffer(); final int yRowStride = planes[0].getRowStride(); final int yPixelStride = planes[0].getPixelStride(); final int uRowStride = planes[1].getRowStride(); final int uPixelStride = planes[1].getPixelStride(); final int vRowStride = planes[2].getRowStride(); final int vPixelStride = planes[2].getPixelStride(); // Decoder crop (coded buffer may be larger than the active picture). final Rect crop = new Rect(image.getCropRect()); if (crop.isEmpty()) { crop.set(0, 0, image.getWidth(), image.getHeight()); } // Amlogic letterboxes the real picture into part of the encoder frame. // Scan every frame until locked; then keep the crop fixed (no jitter). if (!mContentBoundsLocked) { updateContentBounds(yBuf, yRowStride, yPixelStride, crop); } if (!mContentBoundsValid) { mContentBounds.set(crop); mContentBoundsValid = true; } final int srcLeft = mContentBounds.left; final int srcTop = mContentBounds.top; final int srcW = Math.max(2, mContentBounds.width()); final int srcH = Math.max(2, mContentBounds.height()); if (DEBUG && mFramesSent < 5) { Log.i(TAG, "YUV image=" + image.getWidth() + "x" + image.getHeight() + " crop=" + crop.toShortString() + " content=" + mContentBounds.toShortString() + " yStride=" + yRowStride); } int idx = 0; for (int oy = 0; oy < outH; oy++) { final int iy = srcTop + oy * srcH / outH; final int uvRow = iy >> 1; for (int ox = 0; ox < outW; ox++) { final int ix = srcLeft + ox * srcW / outW; final int y = yBuf.get(iy * yRowStride + ix * yPixelStride) & 0xFF; final int uvCol = ix >> 1; final int u = (uBuf.get(uvRow * uRowStride + uvCol * uPixelStride) & 0xFF) - 128; final int v = (vBuf.get(uvRow * vRowStride + uvCol * vPixelStride) & 0xFF) - 128; int r = y + ((359 * v) >> 8); int g = y - ((88 * u + 183 * v) >> 8); int b = y + ((454 * u) >> 8); rgb[idx++] = (byte) clamp(r); rgb[idx++] = (byte) clamp(g); rgb[idx++] = (byte) clamp(b); } } } /** * Detects letterboxed active picture by scanning inward from each edge until a row/column * has enough bright pixels. More robust than a min/max bbox (noise in black bars expands that). */ private void updateContentBounds(ByteBuffer yBuf, int yRowStride, int yPixelStride, Rect crop) { final Rect detected = detectLetterboxByEdges(yBuf, yRowStride, yPixelStride, crop); final float fill = (detected.width() * (float) detected.height()) / Math.max(1, crop.width() * crop.height()); // Amlogic consistently letterboxes into a stable top-left region — lock ASAP. if (fill > 0.05f && fill <= LETTERBOX_FILL_MAX) { mContentBounds.set(detected); mContentBoundsValid = true; mContentBoundsLocked = true; Log.i(TAG, "Content bounds LOCKED " + detected.toShortString() + " fill=" + String.format("%.0f%%", fill * 100f) + " of " + crop.width() + "x" + crop.height()); return; } if (!mContentBoundsValid) { mContentBounds.set(crop); mPendingBounds.set(detected); mContentBoundsValid = true; mStableBoundsCount = 1; Log.i(TAG, "Content bounds fallback full-frame fill=" + String.format("%.0f%%", fill * 100f)); return; } if (boundsSimilar(mPendingBounds, detected, CONTENT_BOUNDS_HYSTERESIS_PX)) { mStableBoundsCount++; if (mStableBoundsCount >= CONTENT_BOUNDS_LOCK_STABLE) { mContentBounds.set(detected); mContentBoundsLocked = true; Log.i(TAG, "Content bounds LOCKED (stable) " + mContentBounds.toShortString()); } } else { mPendingBounds.set(detected); mStableBoundsCount = 1; } } private Rect detectLetterboxByEdges(ByteBuffer yBuf, int yRowStride, int yPixelStride, Rect crop) { final int threshold = BLACK_Y_THRESHOLD; final int minBright = Math.max(3, Math.min(crop.width(), crop.height()) / 64); // Coarse scan — cheap; only runs until lock. final int step = 8; int top = crop.top; for (; top < crop.bottom - 2; top += step) { if (countBrightInRow(yBuf, yRowStride, yPixelStride, crop.left, crop.right, top, threshold) >= minBright) { break; } } int bottom = crop.bottom - 1; for (; bottom > top + 2; bottom -= step) { if (countBrightInRow(yBuf, yRowStride, yPixelStride, crop.left, crop.right, bottom, threshold) >= minBright) { break; } } int left = crop.left; for (; left < crop.right - 2; left += step) { if (countBrightInCol(yBuf, yRowStride, yPixelStride, left, top, bottom, threshold) >= minBright) { break; } } int right = crop.right - 1; for (; right > left + 2; right -= step) { if (countBrightInCol(yBuf, yRowStride, yPixelStride, right, top, bottom, threshold) >= minBright) { break; } } if (right - left < 8 || bottom - top < 8) { return new Rect(crop); } left = Math.max(crop.left, left) & ~1; top = Math.max(crop.top, top) & ~1; right = Math.min(crop.right, right + 1); bottom = Math.min(crop.bottom, bottom + 1); if (((right - left) & 1) != 0) right = Math.min(crop.right, right + 1); if (((bottom - top) & 1) != 0) bottom = Math.min(crop.bottom, bottom + 1); return new Rect(left, top, right, bottom); } private static int countBrightInRow(ByteBuffer yBuf, int yRowStride, int yPixelStride, int x0, int x1, int y, int threshold) { int count = 0; final int row = y * yRowStride; for (int x = x0; x < x1; x += 4) { if ((yBuf.get(row + x * yPixelStride) & 0xFF) > threshold) { count++; } } return count; } private static int countBrightInCol(ByteBuffer yBuf, int yRowStride, int yPixelStride, int x, int y0, int y1, int threshold) { int count = 0; final int xOff = x * yPixelStride; for (int y = y0; y <= y1; y += 4) { if ((yBuf.get(y * yRowStride + xOff) & 0xFF) > threshold) { count++; } } return count; } private static boolean boundsSimilar(Rect a, Rect b, int tolerancePx) { return Math.abs(a.left - b.left) <= tolerancePx && Math.abs(a.top - b.top) <= tolerancePx && Math.abs(a.right - b.right) <= tolerancePx && Math.abs(a.bottom - b.bottom) <= tolerancePx; } private void computeAverageColor(Image image, byte[] scratch) { yuvToRgbDownscale(image, scratch, mOutputWidth, mOutputHeight); long r = 0, g = 0, b = 0; int count = 0; for (int i = 0; i + 2 < scratch.length; i += 3) { r += scratch[i] & 0xFF; g += scratch[i + 1] & 0xFF; b += scratch[i + 2] & 0xFF; count++; } if (count > 0) { mAvgColorResult[0] = (byte) (r / count); mAvgColorResult[1] = (byte) (g / count); mAvgColorResult[2] = (byte) (b / count); } } private static int clamp(int value) { if (value < 0) return 0; if (value > 255) return 255; return value; } private void generateAudioVisualization() { if (mAudioVisualizer == null) return; int[] spectrum = mAudioVisualizer.getFullSpectrum(); int[] visualization = AudioVisualizerController.generateAudioVisualization( mOutputWidth, mOutputHeight, spectrum); byte[] rgb = getRgbBuffer(mOutputWidth, mOutputHeight); for (int i = 0; i < visualization.length && i < rgb.length; i++) { rgb[i] = (byte) (visualization[i] & 0xFF); } if (mAnimationSync != null) { rgb = mAnimationSync.applyAnimationToFrame(rgb); } mListener.sendFrame(rgb, mOutputWidth, mOutputHeight); mRgbBufferIndex = (mRgbBufferIndex + 1) % RGB_BUFFER_RING_SIZE; mFramesSent++; mFpsWindowCount++; maybeLogFps(); } private byte[] getRgbBuffer(int width, int height) { int requiredSize = width * height * BYTES_PER_PIXEL_RGB; byte[] buffer = mRgbBufferRing[mRgbBufferIndex]; if (buffer == null || buffer.length < requiredSize) { buffer = new byte[requiredSize]; mRgbBufferRing[mRgbBufferIndex] = buffer; } return buffer; } private void releaseCodecResources() { if (mVirtualDisplay != null) { try { mVirtualDisplay.release(); } catch (Exception ignored) {} mVirtualDisplay = null; } if (mEncoderSurface != null) { try { mEncoderSurface.release(); } catch (Exception ignored) {} mEncoderSurface = null; } if (mEncoder != null) { try { mEncoder.stop(); } catch (Exception ignored) {} try { mEncoder.release(); } catch (Exception ignored) {} mEncoder = null; } if (mDecoder != null) { try { mDecoder.stop(); } catch (Exception ignored) {} try { mDecoder.release(); } catch (Exception ignored) {} mDecoder = null; } mDecoderConfigured = false; } @Override public void stopRecording() { Log.i(TAG, "Stopping MediaCodec capture"); mRunning = false; setCapturing(false); if (mAudioVisualizer != null) { mAudioVisualizer.stop(); mAudioVisualizer.release(); mAudioVisualizer = null; } if (mCodecHandler != null) { mCodecHandler.removeCallbacksAndMessages(null); } releaseCodecResources(); if (mCodecThread != null) { mCodecThread.quitSafely(); mCodecThread = null; mCodecHandler = null; } mRgbBufferRing = new byte[RGB_BUFFER_RING_SIZE][]; mRgbBufferIndex = 0; mAnimationSync = null; mPreferences = null; mHandler.getLooper().quit(); clearAndDisconnect(); } @Override public void pauseRecording() { Log.i(TAG, "Pausing"); mRunning = false; setCapturing(false); if (mAudioVisualizer != null) { mAudioVisualizer.stop(); } if (mCodecHandler != null) { mCodecHandler.removeCallbacksAndMessages(null); } } @Override public void resumeRecording() { Log.i(TAG, "Resuming"); if (!isCapturing() && mEncoderSurface != null) { startCapture(); } } @Override @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void setOrientation(int orientation) { if (mVirtualDisplay == null || orientation == mCurrentOrientation) return; Log.i(TAG, "Orientation change — restarting MediaCodec pipeline"); mCurrentOrientation = orientation; mRunning = false; setCapturing(false); if (mCodecHandler != null) { mCodecHandler.removeCallbacksAndMessages(null); } // Swap output dimensions; rebuild codecs at new capture size. int tmp = mOutputWidth; mOutputWidth = mOutputHeight; mOutputHeight = tmp; int tmpCap = mCaptureWidth; mCaptureWidth = mCaptureHeight; mCaptureHeight = tmpCap; try { if (mVirtualDisplay != null) { mVirtualDisplay.release(); mVirtualDisplay = null; } if (mEncoderSurface != null) { mEncoderSurface.release(); mEncoderSurface = null; } if (mEncoder != null) { mEncoder.stop(); mEncoder.release(); mEncoder = null; } if (mDecoder != null) { mDecoder.stop(); mDecoder.release(); mDecoder = null; } setupEncoder(); setupDecoder(); mVirtualDisplay = mMediaProjection.createVirtualDisplay( TAG, mCaptureWidth, mCaptureHeight, mDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mEncoderSurface, mDisplayCallback, mHandler); mRgbBufferRing = new byte[RGB_BUFFER_RING_SIZE][]; mRgbBufferIndex = 0; startCapture(); } catch (Exception e) { Log.e(TAG, "Orientation restart failed", e); } } @Override public void clearLights() { super.clearLights(); } }