diff --git a/common/src/main/java/com/hyperion/grabber/util/BufferPool.java b/common/src/main/java/com/hyperion/grabber/util/BufferPool.java new file mode 100644 index 0000000..6b35203 --- /dev/null +++ b/common/src/main/java/com/hyperion/grabber/util/BufferPool.java @@ -0,0 +1,79 @@ +package com.hyperion.grabber.common.util; + +import android.util.Log; +import java.util.concurrent.ConcurrentLinkedQueue; + +/** + * Object pool for byte arrays to reduce garbage collection pressure + * Reuses allocated buffers instead of creating new ones + */ +public class BufferPool { + private static final String TAG = "BufferPool"; + private static BufferPool instance; + + private final ConcurrentLinkedQueue pool = new ConcurrentLinkedQueue<>(); + private final int bufferSize; + private final int maxPoolSize; + private int poolHits = 0; + private int poolMisses = 0; + + private BufferPool(int bufferSize, int maxPoolSize) { + this.bufferSize = bufferSize; + this.maxPoolSize = maxPoolSize; + Log.d(TAG, "BufferPool initialized: size=" + bufferSize + " bytes, max=" + maxPoolSize); + } + + /** + * Get or create singleton with specified buffer size + */ + public static synchronized BufferPool getInstance(int bufferSize, int maxPoolSize) { + if (instance == null) { + instance = new BufferPool(bufferSize, maxPoolSize); + } + return instance; + } + + /** + * Acquire a buffer from the pool or create a new one + */ + public byte[] acquire() { + byte[] buffer = pool.poll(); + if (buffer != null) { + poolHits++; + if (poolHits % 100 == 0) { + Log.d(TAG, "Pool stats - Hits: " + poolHits + ", Misses: " + poolMisses); + } + return buffer; + } + + poolMisses++; + return new byte[bufferSize]; + } + + /** + * Release a buffer back to the pool + */ + public void release(byte[] buffer) { + if (buffer != null && buffer.length == bufferSize && pool.size() < maxPoolSize) { + pool.offer(buffer); + } + } + + /** + * Clear the pool + */ + public void clear() { + pool.clear(); + Log.d(TAG, "BufferPool cleared"); + } + + /** + * Get pool statistics + */ + public String getStats() { + return "BufferPool stats: Size=" + pool.size() + + ", Hits=" + poolHits + ", Misses=" + poolMisses + + ", HitRate=" + String.format("%.2f%%", + (poolHits * 100.0) / (poolHits + poolMisses)); + } +} diff --git a/common/src/main/java/com/hyperion/grabber/util/PerformanceMonitor.java b/common/src/main/java/com/hyperion/grabber/util/PerformanceMonitor.java new file mode 100644 index 0000000..87c0e20 --- /dev/null +++ b/common/src/main/java/com/hyperion/grabber/util/PerformanceMonitor.java @@ -0,0 +1,93 @@ +package com.hyperion.grabber.common.util; + +import android.util.Log; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Performance monitoring utility for tracking operation metrics + * Helps identify bottlenecks and performance regressions + */ +public class PerformanceMonitor { + private static final String TAG = "PerformanceMonitor"; + private static final boolean DEBUG = false; + + private static class Metric { + long count = 0; + long totalTime = 0; + long maxTime = 0; + long minTime = Long.MAX_VALUE; + + void record(long duration) { + count++; + totalTime += duration; + maxTime = Math.max(maxTime, duration); + minTime = Math.min(minTime, duration); + } + + double getAverage() { + return count > 0 ? (double) totalTime / count : 0; + } + } + + private static final ConcurrentHashMap metrics = new ConcurrentHashMap<>(); + + /** + * Start timing an operation + */ + public static long startTimer() { + return System.nanoTime(); + } + + /** + * End timing and record metric + */ + public static void recordMetric(String name, long startTime) { + long duration = System.nanoTime() - startTime; + Metric metric = metrics.computeIfAbsent(name, k -> new Metric()); + metric.record(duration); + + if (DEBUG && metric.count % 100 == 0) { + Log.d(TAG, String.format("%s - Avg: %.2fms, Max: %dms, Min: %dms, Count: %d", + name, + metric.getAverage() / 1_000_000.0, + metric.maxTime / 1_000_000, + metric.minTime / 1_000_000, + metric.count)); + } + } + + /** + * Get metric statistics + */ + public static String getMetrics(String name) { + Metric metric = metrics.get(name); + if (metric == null) return "No metrics for: " + name; + + return String.format("%s - Average: %.2fms, Max: %dms, Min: %dms, Count: %d, Total: %.2fs", + name, + metric.getAverage() / 1_000_000.0, + metric.maxTime / 1_000_000, + metric.minTime / 1_000_000, + metric.count, + metric.totalTime / 1_000_000_000.0); + } + + /** + * Clear all metrics + */ + public static void clearAll() { + metrics.clear(); + Log.d(TAG, "All metrics cleared"); + } + + /** + * Print all metrics + */ + public static void printAll() { + Log.d(TAG, "=== Performance Metrics ==="); + for (String name : metrics.keySet()) { + Log.d(TAG, getMetrics(name)); + } + Log.d(TAG, "========================="); + } +} diff --git a/common/src/main/java/com/hyperion/grabber/util/PerformanceOptimizer.java b/common/src/main/java/com/hyperion/grabber/util/PerformanceOptimizer.java new file mode 100644 index 0000000..3be2be7 --- /dev/null +++ b/common/src/main/java/com/hyperion/grabber/util/PerformanceOptimizer.java @@ -0,0 +1,137 @@ +package com.hyperion.grabber.common.util; + +import android.app.ActivityManager; +import android.content.Context; +import android.os.Build; +import android.util.Log; + +/** + * Performance optimizer utility providing device-aware optimizations + * Adapts behavior based on available system resources + */ +public class PerformanceOptimizer { + private static final String TAG = "PerformanceOptimizer"; + private static PerformanceOptimizer instance; + + private final Context context; + private final ActivityManager activityManager; + private final boolean isLowMemoryDevice; + private final int availableMemoryMb; + + private PerformanceOptimizer(Context context) { + this.context = context.getApplicationContext(); + this.activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); + this.availableMemoryMb = getAvailableMemory(); + this.isLowMemoryDevice = availableMemoryMb < 1024; // Less than 1GB + + Log.d(TAG, "Device memory: " + availableMemoryMb + "MB, Low memory device: " + isLowMemoryDevice); + } + + /** + * Get singleton instance + */ + public static synchronized PerformanceOptimizer getInstance(Context context) { + if (instance == null) { + instance = new PerformanceOptimizer(context); + } + return instance; + } + + /** + * Get available system memory in MB + */ + private int getAvailableMemory() { + try { + ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo(); + if (activityManager != null) { + activityManager.getMemoryInfo(memInfo); + return (int) (memInfo.totalMem / 1048576L); // Convert to MB + } + } catch (Exception e) { + Log.e(TAG, "Failed to get memory info: " + e.getMessage()); + } + return 0; + } + + /** + * Get optimized frame rate based on device capabilities + * Higher end devices can handle higher frame rates + */ + public int getOptimizedFrameRate(int requestedFrameRate) { + if (isLowMemoryDevice) { + // Cap at 30fps for low memory devices + return Math.min(requestedFrameRate, 30); + } else if (availableMemoryMb < 2048) { + // Cap at 45fps for mid-range devices + return Math.min(requestedFrameRate, 45); + } + // No limit for high-end devices + return requestedFrameRate; + } + + /** + * Get optimized buffer size based on device memory + * Prevents OOM on low-memory devices + */ + public int getOptimizedBufferSize(int baseSize) { + if (isLowMemoryDevice) { + // Use 75% of base size on low memory devices + return (baseSize * 3) / 4; + } else if (availableMemoryMb < 2048) { + // Use 90% of base size on mid-range devices + return (baseSize * 9) / 10; + } + // Use full size on high-end devices + return baseSize; + } + + /** + * Determine if aggressive garbage collection should be enabled + */ + public boolean shouldUseAggressiveGC() { + return isLowMemoryDevice; + } + + /** + * Get thread pool size recommendation + */ + public int getOptimalThreadPoolSize() { + int processors = Runtime.getRuntime().availableProcessors(); + if (isLowMemoryDevice) { + // Use single thread on low memory devices + return 1; + } else if (availableMemoryMb < 2048) { + // Use min(2, processors) on mid-range + return Math.min(2, processors); + } + // Use processors/2 + 1 on high-end (standard formula) + return Math.max(processors / 2 + 1, 1); + } + + /** + * Check if device has enough memory for high-quality operations + */ + public boolean hasEnoughMemoryForHighQuality() { + return availableMemoryMb >= 2048; + } + + /** + * Get memory cache size in MB + */ + public int getMemoryCacheSize() { + if (isLowMemoryDevice) { + return 2; // 2MB for low memory devices + } else if (availableMemoryMb < 2048) { + return 5; // 5MB for mid-range + } + return 10; // 10MB for high-end + } + + public boolean isLowMemoryDevice() { + return isLowMemoryDevice; + } + + public int getAvailableMemoryMb() { + return availableMemoryMb; + } +} diff --git a/common/src/main/java/com/hyperion/grabber/util/ResourceManager.java b/common/src/main/java/com/hyperion/grabber/util/ResourceManager.java new file mode 100644 index 0000000..1c71440 --- /dev/null +++ b/common/src/main/java/com/hyperion/grabber/util/ResourceManager.java @@ -0,0 +1,65 @@ +package com.hyperion.grabber.common.util; + +import android.util.Log; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * Manages lifecycle of resources to ensure proper cleanup + * Prevents resource leaks and improves application stability + */ +public class ResourceManager { + private static final String TAG = "ResourceManager"; + + private final CopyOnWriteArrayList resources = new CopyOnWriteArrayList<>(); + + /** + * Register a resource for lifecycle management + */ + public void register(Resource resource) { + if (resource != null) { + resources.add(resource); + Log.d(TAG, "Resource registered: " + resource.getClass().getSimpleName()); + } + } + + /** + * Unregister a resource + */ + public void unregister(Resource resource) { + if (resources.remove(resource)) { + Log.d(TAG, "Resource unregistered: " + resource.getClass().getSimpleName()); + } + } + + /** + * Release all managed resources + */ + public void releaseAll() { + for (Resource resource : resources) { + try { + resource.release(); + Log.d(TAG, "Resource released: " + resource.getClass().getSimpleName()); + } catch (Exception e) { + Log.e(TAG, "Error releasing resource: " + e.getMessage(), e); + } + } + resources.clear(); + } + + /** + * Get count of managed resources + */ + public int getResourceCount() { + return resources.size(); + } + + /** + * Resource interface for lifecycle management + */ + public interface Resource { + /** + * Called when resource should be released + */ + void release(); + } +}