feat: plog & limited hardware support

This commit is contained in:
zhoubinjia committed 2026-01-14 14:20:52 +08:00
1 parent c510d671af
commit c1020d11d2
28 files changed
+1224 -293

No files matched your search

@@ -29,9 +29,9 @@ class BillingManagerImpl(private val context: Context) : BillingManager {
handlePurchase(purchase)
}
} else if (billingResult.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) {
Log.d(TAG, "User canceled the purchase")
PLog.d(TAG, "User canceled the purchase")
} else {
Log.e(TAG, "Purchase error: ${billingResult.debugMessage}")
PLog.e(TAG, "Purchase error: ${billingResult.debugMessage}")
}
}
@@ -48,13 +48,13 @@ class BillingManagerImpl(private val context: Context) : BillingManager {
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
Log.d(TAG, "Billing setup finished")
PLog.d(TAG, "Billing setup finished")
queryPurchases()
}
}
override fun onBillingServiceDisconnected() {
Log.d(TAG, "Billing service disconnected, retrying...")
PLog.d(TAG, "Billing service disconnected, retrying...")
// Retry logic if needed
}
})
@@ -69,7 +69,7 @@ class BillingManagerImpl(private val context: Context) : BillingManager {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
val purchased = purchases.any { it.purchaseState == Purchase.PurchaseState.PURCHASED }
_isPurchased.value = purchased
Log.d(TAG, "Purchases queried: $purchased")
PLog.d(TAG, "Purchases queried: $purchased")
// If purchased but not acknowledged, acknowledge it
purchases.forEach { purchase ->
@@ -87,7 +87,7 @@ class BillingManagerImpl(private val context: Context) : BillingManager {
.build()
billingClient.acknowledgePurchase(params) { billingResult ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
Log.d(TAG, "Purchase acknowledged")
PLog.d(TAG, "Purchase acknowledged")
_isPurchased.value = true
}
}
@@ -118,7 +118,7 @@ class BillingManagerImpl(private val context: Context) : BillingManager {
.build()
billingClient.launchBillingFlow(activity, flowParams)
} else {
Log.e(TAG, "Failed to query product details: ${billingResult.debugMessage}")
PLog.e(TAG, "Failed to query product details: ${billingResult.debugMessage}")
}
}
}
@@ -14,9 +14,9 @@ import android.media.ImageReader
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.util.Size
import android.view.Surface
import androidx.exifinterface.media.ExifInterface
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.utils.OrientationObserver
import com.hinnka.mycamera.utils.YuvProcessor
import kotlinx.coroutines.flow.MutableStateFlow
@@ -65,7 +65,12 @@ class Camera2Controller(private val context: Context) {
private var cameraThread: HandlerThread? = null
private var cameraHandler: Handler? = null
private var cachedCharacteristics: CameraCharacteristics? = null
private var cachedSensorOrientation: Int = 0
private var cachedLensFacing: Int = CameraCharacteristics.LENS_FACING_BACK
private var cachedHardwareLevel: Int = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED
private val _state = MutableStateFlow(CameraState())
val state: StateFlow<CameraState> = _state.asStateFlow()
@@ -120,6 +125,7 @@ class Camera2Controller(private val context: Context) {
* 初始化相机
*/
fun initialize() {
PLog.i(TAG, "初始化相机控制器")
startBackgroundThread()
discoverCameras()
}
@@ -136,7 +142,7 @@ class Camera2Controller(private val context: Context) {
cameraThread = null
cameraHandler = null
} catch (e: InterruptedException) {
Log.e(TAG, "Error stopping background thread", e)
PLog.e(TAG, "Error stopping background thread", e)
}
}
@@ -145,17 +151,21 @@ class Camera2Controller(private val context: Context) {
*/
private fun discoverCameras() {
val cameras = cameraDiscovery.discoverAllCameras()
Log.d(TAG, "Discovered ${cameras.size} cameras:")
PLog.d(TAG, "Discovered ${cameras.size} cameras:")
PLog.d(TAG, "发现 ${cameras.size} 个摄像头")
cameras.forEach { cam ->
Log.d(TAG, " - ${cam.cameraId}: ${cam.lensType}, intrinsicZoom=${cam.intrinsicZoomRatio}")
PLog.d(TAG, " - ${cam.cameraId}: ${cam.lensType}, intrinsicZoom=${cam.intrinsicZoomRatio}")
PLog.d(TAG, "摄像头: ${cam.cameraId}, 类型: ${cam.lensType}, 变焦: ${cam.intrinsicZoomRatio}")
}
// 默认选择主摄
val defaultCamera = cameras.firstOrNull { it.lensType == LensType.BACK_MAIN }
?: cameras.firstOrNull { it.lensFacing == CameraCharacteristics.LENS_FACING_BACK }
?: cameras.firstOrNull()
PLog.i(TAG, "选择默认摄像头: ${defaultCamera?.cameraId}, 类型: ${defaultCamera?.lensType}")
_state.value = _state.value.copy(
availableCameras = cameras,
currentCameraId = defaultCamera?.cameraId ?: "",
@@ -167,30 +177,63 @@ class Camera2Controller(private val context: Context) {
/**
* 打开相机并开始预览
*
*
* @param surfaceTexture SurfaceTexture 用于预览
*/
@SuppressLint("MissingPermission")
fun openCamera(surfaceTexture: SurfaceTexture) {
// 先关闭旧的相机和资源,防止资源泄漏
closeCamera()
val cameraId = _state.value.currentCameraId
val aspectRatio = _state.value.aspectRatio
if (cameraId.isEmpty()) {
Log.e(TAG, "No camera ID set")
PLog.e(TAG, "No camera ID set")
return
}
PLog.i(TAG, "打开相机: $cameraId, 画面比例: ${aspectRatio.getDisplayName()}")
val previewSize = CameraUtils.getFixedPreviewSize(context, cameraId, aspectRatio)
surfaceTexture.setDefaultBufferSize(previewSize.width, previewSize.height)
try {
try {
cachedCharacteristics = cameraManager.getCameraCharacteristics(cameraId)
// 缓存固定属性(传感器方向、镜头朝向、硬件级别)
// 这些值在相机生命周期内不会改变,避免在每帧预览中重复获取
cachedSensorOrientation = cachedCharacteristics?.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0
cachedLensFacing = cachedCharacteristics?.get(CameraCharacteristics.LENS_FACING)
?: CameraCharacteristics.LENS_FACING_BACK
cachedHardwareLevel = cachedCharacteristics?.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)
?: CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED
val hardwareLevelName = when (cachedHardwareLevel) {
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY -> "LEGACY"
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED -> "LIMITED"
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL -> "FULL"
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3 -> "LEVEL_3"
else -> "UNKNOWN($cachedHardwareLevel)"
}
PLog.i(TAG, "Camera characteristics cached - ID: $cameraId, Hardware Level: $hardwareLevelName")
} catch (e: Exception) {
PLog.e(TAG, "Failed to cache camera characteristics", e)
cachedCharacteristics = null
cachedSensorOrientation = 0
cachedLensFacing = CameraCharacteristics.LENS_FACING_BACK
}
// 配置 SurfaceTexture
previewSurface = Surface(surfaceTexture)
// val characteristics = cameraManager.getCameraCharacteristics(cameraId)
// HighResolutionHelper.logResolutionCapabilities(characteristics)
// 创建 ImageReader 用于拍照 (使用 YUV 格式)
val captureSize = CameraUtils.getBestCaptureSize(context, cameraId, aspectRatio)
PLog.d(TAG, "拍照尺寸: ${captureSize.width}x${captureSize.height}, 预览尺寸: ${previewSize.width}x${previewSize.height}")
imageReader = ImageReader.newInstance(
captureSize.width,
captureSize.height,
@@ -337,7 +380,7 @@ class Camera2Controller(private val context: Context) {
}
}
// Log.d(TAG, "avgLum: ${weightedSumLuminance / totalWeight}")
// PLog.d(TAG, "avgLum: ${weightedSumLuminance / totalWeight}")
// Calculate Software Auto Metering
calculateAutoMetering(totalWeight, weightedSumLuminance)
@@ -364,31 +407,31 @@ class Camera2Controller(private val context: Context) {
return@setOnImageAvailableListener
}
} catch (e: Exception) {
Log.e(TAG, "Failed to calculate histogram", e)
PLog.e(TAG, "Failed to calculate histogram", e)
} finally {
image.close()
}
}, cameraHandler)
}
Log.d(TAG, "Opening camera: $cameraId")
PLog.d(TAG, "Opening camera: $cameraId")
cameraManager.openCamera(cameraId, object : CameraDevice.StateCallback() {
override fun onOpened(camera: CameraDevice) {
Log.d(TAG, "Camera opened: ${camera.id}")
PLog.d(TAG, "Camera opened: ${camera.id}")
cameraDevice = camera
createPreviewSession()
}
override fun onDisconnected(camera: CameraDevice) {
Log.w(TAG, "Camera disconnected: ${camera.id}")
PLog.w(TAG, "Camera disconnected: ${camera.id}")
camera.close()
cameraDevice = null
_state.value = _state.value.copy(isPreviewActive = false)
}
override fun onError(camera: CameraDevice, error: Int) {
Log.e(TAG, "Camera error: ${camera.id}, error=$error")
PLog.e(TAG, "Camera error: ${camera.id}, error=$error")
camera.close()
cameraDevice = null
_state.value = _state.value.copy(isPreviewActive = false)
@@ -396,9 +439,9 @@ class Camera2Controller(private val context: Context) {
}, cameraHandler)
} catch (e: CameraAccessException) {
Log.e(TAG, "Failed to open camera", e)
PLog.e(TAG, "Failed to open camera", e)
} catch (e: SecurityException) {
Log.e(TAG, "Camera permission denied", e)
PLog.e(TAG, "Camera permission denied", e)
}
}
@@ -488,7 +531,7 @@ class Camera2Controller(private val context: Context) {
val builder = previewRequestBuilder
if (device == null || session == null || builder == null) {
Log.v(TAG, "calculateAutoMetering: camera not ready, skipping update")
PLog.v(TAG, "calculateAutoMetering: camera not ready, skipping update")
return
}
@@ -501,11 +544,11 @@ class Camera2Controller(private val context: Context) {
)
meteringSkipFrames = 5
} catch (e: CameraAccessException) {
Log.e(TAG, "Failed to update exposure: ${e.message}")
PLog.e(TAG, "Failed to update exposure: ${e.message}")
} catch (e: IllegalStateException) {
Log.w(TAG, "Failed to update exposure - camera closed: ${e.message}")
PLog.w(TAG, "Failed to update exposure - camera closed: ${e.message}")
} catch (e: Exception) {
Log.e(TAG, "Failed to update exposure: ${e.message}")
PLog.e(TAG, "Failed to update exposure: ${e.message}")
}
}
}
@@ -549,14 +592,14 @@ class Camera2Controller(private val context: Context) {
}
override fun onConfigureFailed(session: CameraCaptureSession) {
Log.e(TAG, "Session configuration failed")
PLog.e(TAG, "Session configuration failed")
}
}
)
device.createCaptureSession(sessionConfig)
} catch (e: CameraAccessException) {
Log.e(TAG, "Failed to create preview session", e)
PLog.e(TAG, "Failed to create preview session", e)
}
}
@@ -571,42 +614,48 @@ class Camera2Controller(private val context: Context) {
}
_state.value = _state.value.copy(isPreviewActive = true)
Log.d(TAG, "Preview started")
PLog.d(TAG, "Preview started")
} catch (e: CameraAccessException) {
Log.e(TAG, "Failed to start preview", e)
PLog.e(TAG, "Failed to start preview", e)
} catch (e: IllegalStateException) {
Log.e(TAG, "Failed to start preview - illegal state", e)
PLog.e(TAG, "Failed to start preview - illegal state", e)
} catch (e: IllegalArgumentException) {
Log.e(TAG, "Failed to start preview - unconfigured surface", e)
PLog.e(TAG, "Failed to start preview - unconfigured surface", e)
}
}
/**
* 设置 Flat Profile(平坦色调曲线)
*
* LIMITED 硬件级别不支持手动 Tonemap 控制
* 只在 FULL 或 LEVEL_3 设备上启用,否则会导致相机服务崩溃
*/
private fun setupFlatProfileRequest(builder: CaptureRequest.Builder) {
// 检查硬件级别:只有 FULL 或 LEVEL_3 支持手动 Tonemap
val isFullOrAbove = cachedHardwareLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL ||
cachedHardwareLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3
if (!isFullOrAbove) {
// LIMITED 或 LEGACY 设备:跳过 Tonemap 设置
PLog.d(TAG, "跳过 Tonemap 设置 (硬件级别不支持: $cachedHardwareLevel)")
return
}
try {
// 只在支持的设备上设置 Tonemap
builder.set(CaptureRequest.TONEMAP_MODE, CaptureRequest.TONEMAP_MODE_PRESET_CURVE)
builder.set(CaptureRequest.TONEMAP_PRESET_CURVE, CaptureRequest.TONEMAP_PRESET_CURVE_SRGB)
PLog.d(TAG, "已启用 Flat Profile (TONEMAP_PRESET_CURVE_SRGB)")
} catch (e: Exception) {
PLog.e(TAG, "Failed to set tonemap (ignoring)", e)
}
// 1. 禁用所有场景特效
// builder.set(CaptureRequest.CONTROL_SCENE_MODE, CaptureRequest.CONTROL_SCENE_MODE_DISABLED)
// builder.set(CaptureRequest.CONTROL_EFFECT_MODE, CaptureRequest.CONTROL_EFFECT_MODE_OFF)
// builder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE, CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_OFF)
// 2. 强制使用矩阵色彩校正(去除厂商滤镜倾向)
// builder.set(CaptureRequest.COLOR_CORRECTION_MODE, CaptureRequest.COLOR_CORRECTION_MODE_TRANSFORM_MATRIX)
// 3. 覆盖 Tone Mapping(关键:去除 S 曲线)
builder.set(CaptureRequest.TONEMAP_MODE, CaptureRequest.TONEMAP_MODE_PRESET_CURVE)
builder.set(CaptureRequest.TONEMAP_PRESET_CURVE, CaptureRequest.TONEMAP_PRESET_CURVE_SRGB)
//
// // 生成标准 Gamma 2.2 曲线 (比纯线性更接近人眼感知的“标准灰片”)
// // 如果直接用 Linear,画面会极其暗,LUT 很难拉回来
// val curvePoints = FloatArray(64 * 2) // 64个控制点
// for (i in 0 until 64) {
// val input = i / 63.0f
// val output = input.toDouble().pow(1.0 / 2.2).toFloat() // Gamma 2.2
// curvePoints[i * 2] = input
// curvePoints[i * 2 + 1] = output
// }
// val gammaCurve = TonemapCurve(curvePoints, curvePoints, curvePoints)
// builder.set(CaptureRequest.TONEMAP_CURVE, gammaCurve)
// 4. 关闭锐化
// builder.set(CaptureRequest.EDGE_MODE, CaptureRequest.EDGE_MODE_OFF)
}
@@ -680,14 +729,14 @@ class Camera2Controller(private val context: Context) {
// 拍摄时设置低帧率范围以支持长曝光
if (isCapture) {
try {
val characteristics = cameraManager.getCameraCharacteristics(state.currentCameraId)
val characteristics = cachedCharacteristics ?: cameraManager.getCameraCharacteristics(state.currentCameraId)
val availableFpsRanges = characteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)
val lowestFpsRange = availableFpsRanges?.minByOrNull { it.upper }
lowestFpsRange?.let {
builder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, it)
}
} catch (e: Exception) {
Log.e(TAG, "Failed to set FPS range", e)
PLog.e(TAG, "Failed to set FPS range", e)
}
}
}
@@ -771,9 +820,9 @@ class Camera2Controller(private val context: Context) {
private fun applyZoomSettings(builder: CaptureRequest.Builder, state: CameraState) {
val cameraId = state.currentCameraId
if (cameraId.isEmpty() || state.zoomRatio <= 1f) return
try {
val characteristics = cameraManager.getCameraCharacteristics(cameraId)
val characteristics = cachedCharacteristics ?: cameraManager.getCameraCharacteristics(cameraId)
val activeRect = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE) ?: return
val centerX = activeRect.width() / 2
@@ -789,7 +838,7 @@ class Camera2Controller(private val context: Context) {
)
builder.set(CaptureRequest.SCALER_CROP_REGION, cropRect)
} catch (e: Exception) {
Log.e(TAG, "Failed to apply zoom settings", e)
PLog.e(TAG, "Failed to apply zoom settings", e)
}
}
@@ -799,33 +848,14 @@ class Camera2Controller(private val context: Context) {
* 获取传感器方向(供外部 YUV 处理使用)
*/
fun getSensorOrientation(): Int {
val cameraId = _state.value.currentCameraId
if (cameraId.isEmpty()) return 0
return try {
val characteristics = cameraManager.getCameraCharacteristics(cameraId)
characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0
} catch (e: Exception) {
Log.e(TAG, "Failed to get sensor orientation", e)
0
}
return cachedSensorOrientation
}
/**
* 获取镜头朝向
*/
fun getLensFacing(): Int {
val cameraId = _state.value.currentCameraId
if (cameraId.isEmpty()) return CameraCharacteristics.LENS_FACING_BACK
return try {
val characteristics = cameraManager.getCameraCharacteristics(cameraId)
characteristics.get(CameraCharacteristics.LENS_FACING)
?: CameraCharacteristics.LENS_FACING_BACK
} catch (e: Exception) {
Log.e(TAG, "Failed to get lens facing", e)
CameraCharacteristics.LENS_FACING_BACK
}
return cachedLensFacing
}
// ==================== 镜头切换 ====================
@@ -860,14 +890,14 @@ class Camera2Controller(private val context: Context) {
fun switchToLens(lensType: LensType) {
val cameras = _state.value.availableCameras
val currentLensType = _state.value.currentLensType
if (currentLensType == lensType) return
val targetCamera = cameras.find { it.lensType == lensType }
targetCamera?.let { cam ->
Log.d(TAG, "Switching to lens: $lensType, cameraId: ${cam.cameraId}")
PLog.d(TAG, "Switching to lens: $lensType, cameraId: ${cam.cameraId}")
// 关闭当前相机
closeCamera()
@@ -879,7 +909,7 @@ class Camera2Controller(private val context: Context) {
)
// 注意:需要外部重新调用 openCamera
} ?: Log.w(TAG, "Camera with lens type $lensType not found")
} ?: PLog.w(TAG, "Camera with lens type $lensType not found")
}
/**
@@ -890,7 +920,7 @@ class Camera2Controller(private val context: Context) {
val targetCamera = cameras.find { it.cameraId == cameraId }
targetCamera?.let { cam ->
Log.d(TAG, "Switching to camera ID: $cameraId")
PLog.d(TAG, "Switching to camera ID: $cameraId")
// 关闭当前相机
closeCamera()
@@ -901,7 +931,7 @@ class Camera2Controller(private val context: Context) {
currentLensType = cam.lensType,
zoomRatio = 1f
)
} ?: Log.w(TAG, "Camera with ID $cameraId not found")
} ?: PLog.w(TAG, "Camera with ID $cameraId not found")
}
// ==================== 曝光控制 ====================
@@ -1019,18 +1049,18 @@ class Camera2Controller(private val context: Context) {
private fun supportsManualWhiteBalance(): Boolean {
val cameraId = _state.value.currentCameraId
if (cameraId.isEmpty()) return false
return try {
val characteristics = cameraManager.getCameraCharacteristics(cameraId)
val characteristics = cachedCharacteristics ?: cameraManager.getCameraCharacteristics(cameraId)
val hardwareLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)
val isSupported = hardwareLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL ||
hardwareLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3
Log.d(TAG, "Hardware level: $hardwareLevel, Manual WB supported: $isSupported")
PLog.d(TAG, "Hardware level: $hardwareLevel, Manual WB supported: $isSupported")
isSupported
} catch (e: Exception) {
Log.e(TAG, "Failed to check hardware level", e)
PLog.e(TAG, "Failed to check hardware level", e)
false
}
}
@@ -1041,9 +1071,9 @@ class Camera2Controller(private val context: Context) {
private fun getSupportedAwbModes(): IntArray {
val cameraId = _state.value.currentCameraId
if (cameraId.isEmpty()) return intArrayOf(CameraMetadata.CONTROL_AWB_MODE_AUTO)
return try {
val characteristics = cameraManager.getCameraCharacteristics(cameraId)
val characteristics = cachedCharacteristics ?: cameraManager.getCameraCharacteristics(cameraId)
characteristics.get(CameraCharacteristics.CONTROL_AWB_AVAILABLE_MODES)
?: intArrayOf(CameraMetadata.CONTROL_AWB_MODE_AUTO)
} catch (e: Exception) {
@@ -1065,7 +1095,7 @@ class Camera2Controller(private val context: Context) {
val gains = kelvinToRggbGains(_state.value.awbTemperature)
set(CaptureRequest.COLOR_CORRECTION_GAINS, gains)
Log.d(TAG, "Manual AWB enabled with temperature: ${_state.value.awbTemperature}K")
PLog.d(TAG, "Manual AWB enabled with temperature: ${_state.value.awbTemperature}K")
} else {
set(CaptureRequest.COLOR_CORRECTION_MODE, CaptureRequest.COLOR_CORRECTION_MODE_FAST)
}
@@ -1097,7 +1127,7 @@ class Camera2Controller(private val context: Context) {
val gains = kelvinToRggbGains(clampedKelvin)
set(CaptureRequest.COLOR_CORRECTION_GAINS, gains)
Log.d(TAG, "AWB temperature set to: ${clampedKelvin}K (manual), gains: R=${gains.red}, G=${gains.greenEven}, B=${gains.blue}")
PLog.d(TAG, "AWB temperature set to: ${clampedKelvin}K (manual), gains: R=${gains.red}, G=${gains.greenEven}, B=${gains.blue}")
updatePreview()
}
} else {
@@ -1112,7 +1142,7 @@ class Camera2Controller(private val context: Context) {
previewRequestBuilder?.apply {
set(CaptureRequest.CONTROL_AWB_MODE, presetMode)
set(CaptureRequest.COLOR_CORRECTION_MODE, CaptureRequest.COLOR_CORRECTION_MODE_FAST)
Log.d(TAG, "AWB temperature set to: ${clampedKelvin}K (preset mode: ${getAwbModeName(presetMode)})")
PLog.d(TAG, "AWB temperature set to: ${clampedKelvin}K (preset mode: ${getAwbModeName(presetMode)})")
updatePreview()
}
}
@@ -1221,7 +1251,7 @@ class Camera2Controller(private val context: Context) {
blue = blue.coerceIn(0f, 255f)
}
Log.d(TAG, "kelvinToRggbGains: ${kelvin}K -> RGB($red, $green, $blue)")
PLog.d(TAG, "kelvinToRggbGains: ${kelvin}K -> RGB($red, $green, $blue)")
// Camera2 特定的增益计算:
// 红色和蓝色通道乘以2,绿色通道保持归一化
@@ -1245,17 +1275,17 @@ class Camera2Controller(private val context: Context) {
val builder = previewRequestBuilder
if (device == null || session == null || builder == null) {
Log.v(TAG, "updatePreview: camera not ready (device=$device, session=$session, builder=$builder)")
PLog.v(TAG, "updatePreview: camera not ready (device=$device, session=$session, builder=$builder)")
return
}
try {
session.setRepeatingRequest(builder.build(), previewCallback, cameraHandler)
} catch (e: CameraAccessException) {
Log.e(TAG, "Failed to update preview", e)
PLog.e(TAG, "Failed to update preview", e)
} catch (e: IllegalStateException) {
// 相机已关闭或处于错误状态
Log.w(TAG, "Failed to update preview - camera closed or in error state", e)
PLog.w(TAG, "Failed to update preview - camera closed or in error state", e)
}
}
@@ -1268,9 +1298,9 @@ class Camera2Controller(private val context: Context) {
fun setZoomRatio(ratio: Float) {
val cameraId = _state.value.currentCameraId
if (cameraId.isEmpty()) return
try {
val characteristics = cameraManager.getCameraCharacteristics(cameraId)
val characteristics = cachedCharacteristics ?: cameraManager.getCameraCharacteristics(cameraId)
val maxZoom = characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM) ?: 1f
val clampedRatio = ratio.coerceIn(1f, maxZoom)
@@ -1295,10 +1325,10 @@ class Camera2Controller(private val context: Context) {
updatePreview()
}
Log.d(TAG, "setZoomRatio: $ratio -> $clampedRatio")
PLog.d(TAG, "setZoomRatio: $ratio -> $clampedRatio")
} catch (e: Exception) {
Log.e(TAG, "Failed to set zoom", e)
PLog.e(TAG, "Failed to set zoom", e)
}
}
@@ -1316,9 +1346,9 @@ class Camera2Controller(private val context: Context) {
isFocusing = true,
focusSuccess = null
)
try {
val characteristics = cameraManager.getCameraCharacteristics(cameraId)
val characteristics = cachedCharacteristics ?: cameraManager.getCameraCharacteristics(cameraId)
val activeRect = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE) ?: return
// 计算对焦区域
@@ -1367,7 +1397,7 @@ class Camera2Controller(private val context: Context) {
}, 2500)
} catch (e: Exception) {
Log.e(TAG, "Failed to focus", e)
PLog.e(TAG, "Failed to focus", e)
_state.value = _state.value.copy(isFocusing = false, focusSuccess = false)
}
}
@@ -1422,6 +1452,8 @@ class Camera2Controller(private val context: Context) {
val device = cameraDevice ?: return
val reader = imageReader ?: return
PLog.i(TAG, "开始拍照 - 闪光模式: ${_state.value.flashMode}, ISO模式: ${if (_state.value.isIsoAuto) "自动" else "手动(${_state.value.iso})"}")
// 播放快门音效
onPlayShutterSound?.invoke()
@@ -1437,14 +1469,17 @@ class Camera2Controller(private val context: Context) {
if (needsPrecapture) {
// 自动曝光 + 单次闪光:需要先触发预闪流程
PLog.d(TAG, "使用预闪流程")
triggerPrecaptureAndCapture(device, reader)
} else {
// 其他情况(手动曝光、手电筒模式、不使用闪光灯):直接拍照
PLog.d(TAG, "直接拍照")
performCapture(device, reader)
}
} catch (e: CameraAccessException) {
Log.e(TAG, "Failed to capture", e)
PLog.e(TAG, "Failed to capture", e)
PLog.e(TAG, "拍照失败", e)
_state.value = _state.value.copy(isCapturing = false)
}
}
@@ -1465,7 +1500,7 @@ class Camera2Controller(private val context: Context) {
result: TotalCaptureResult
) {
val aeState = result.get(CaptureResult.CONTROL_AE_STATE)
Log.d(TAG, "Precapture AE state: $aeState")
PLog.d(TAG, "Precapture AE state: $aeState")
// 等待 AE 收敛完成
// AE_STATE_CONVERGED (2) 或 AE_STATE_FLASH_REQUIRED (4) 表示可以拍照了
@@ -1490,14 +1525,14 @@ class Camera2Controller(private val context: Context) {
request: CaptureRequest,
failure: CaptureFailure
) {
Log.e(TAG, "Precapture failed: ${failure.reason}")
PLog.e(TAG, "Precapture failed: ${failure.reason}")
// 即使预闪失败,也尝试拍照
performCapture(device, reader)
}
}, cameraHandler)
}
} catch (e: Exception) {
Log.e(TAG, "Failed to trigger precapture", e)
PLog.e(TAG, "Failed to trigger precapture", e)
// 出错时直接拍照
performCapture(device, reader)
}
@@ -1528,7 +1563,7 @@ class Camera2Controller(private val context: Context) {
}
}
Log.d(TAG, "Capture with ISO: ${_state.value.iso}, shutterSpeed: ${_state.value.shutterSpeed}, isAutoExposure: ${_state.value.isAutoExposure}")
PLog.d(TAG, "Capture with ISO: ${_state.value.iso}, shutterSpeed: ${_state.value.shutterSpeed}, isAutoExposure: ${_state.value.isAutoExposure}")
}
captureSession?.capture(captureBuilder.build(), object : CameraCaptureSession.CaptureCallback() {
@@ -1539,7 +1574,7 @@ class Camera2Controller(private val context: Context) {
) {
// 保存拍摄结果用于提取 EXIF
lastCaptureResult = result
Log.d(TAG, "Capture completed")
PLog.d(TAG, "Capture completed")
// 关键修复:拍照完成后重置预览流的预闪触发器
// 这样可以避免预闪状态影响后续的预览(例如手电筒模式变暗)
@@ -1551,7 +1586,7 @@ class Camera2Controller(private val context: Context) {
request: CaptureRequest,
failure: CaptureFailure
) {
Log.e(TAG, "Capture failed: ${failure.reason}")
PLog.e(TAG, "Capture failed: ${failure.reason}")
_state.value = _state.value.copy(isCapturing = false)
// 即使拍照失败,也要重置预览
@@ -1560,7 +1595,7 @@ class Camera2Controller(private val context: Context) {
}, cameraHandler)
} catch (e: CameraAccessException) {
Log.e(TAG, "Failed to perform capture", e)
PLog.e(TAG, "Failed to perform capture", e)
_state.value = _state.value.copy(isCapturing = false)
}
}
@@ -1577,7 +1612,7 @@ class Camera2Controller(private val context: Context) {
val builder = previewRequestBuilder
if (device == null || session == null || builder == null) {
Log.v(TAG, "resetPreviewAfterCapture: camera not ready, skipping")
PLog.v(TAG, "resetPreviewAfterCapture: camera not ready, skipping")
return
}
@@ -1592,13 +1627,13 @@ class Camera2Controller(private val context: Context) {
// 发送重置后的预览请求
session.setRepeatingRequest(builder.build(), previewCallback, cameraHandler)
Log.d(TAG, "Preview reset after capture")
PLog.d(TAG, "Preview reset after capture")
} catch (e: CameraAccessException) {
Log.e(TAG, "Failed to reset preview after capture", e)
PLog.e(TAG, "Failed to reset preview after capture", e)
} catch (e: IllegalStateException) {
Log.w(TAG, "Failed to reset preview - camera closed", e)
PLog.w(TAG, "Failed to reset preview - camera closed", e)
} catch (e: Exception) {
Log.e(TAG, "Failed to reset preview after capture", e)
PLog.e(TAG, "Failed to reset preview after capture", e)
}
}
@@ -1619,10 +1654,10 @@ class Camera2Controller(private val context: Context) {
var aperture: Float? = null
var focalLength: Float? = null
var focalLength35mm: Int? = null
try {
val characteristics = cameraManager.getCameraCharacteristics(cameraId)
val characteristics = cachedCharacteristics ?: cameraManager.getCameraCharacteristics(cameraId)
// 光圈值(取第一个可用光圈)
val apertures = characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_APERTURES)
aperture = apertures?.firstOrNull()
@@ -1636,7 +1671,7 @@ class Camera2Controller(private val context: Context) {
}
} catch (e: Exception) {
Log.e(TAG, "Failed to get camera characteristics for EXIF", e)
PLog.e(TAG, "Failed to get camera characteristics for EXIF", e)
}
// 从 TotalCaptureResult 获取曝光信息
@@ -1648,11 +1683,11 @@ class Camera2Controller(private val context: Context) {
// 如果有实时的光圈/焦距,使用实时值
result?.get(CaptureResult.LENS_APERTURE)?.let { aperture = it }
result?.get(CaptureResult.LENS_FOCAL_LENGTH)?.let {
Log.d(TAG, "buildCaptureInfo: $zoomRatio")
PLog.d(TAG, "buildCaptureInfo: $zoomRatio")
focalLength = it * zoomRatio
// 重新计算35mm等效焦距
try {
val characteristics = cameraManager.getCameraCharacteristics(cameraId)
val characteristics = cachedCharacteristics ?: cameraManager.getCameraCharacteristics(cameraId)
focalLength35mm = calculate35mmEquivalent(characteristics, it)?.times(zoomRatio)?.roundToInt()
} catch (e: Exception) {
// 忽略
@@ -1705,9 +1740,9 @@ class Camera2Controller(private val context: Context) {
fun capturePreviewFrame() {
shouldCapturePreviewFrame = true
}
// ==================== 生命周期 ====================
/**
* 关闭相机
*/
@@ -1715,24 +1750,30 @@ class Camera2Controller(private val context: Context) {
try {
captureSession?.close()
captureSession = null
cameraDevice?.close()
cameraDevice = null
imageReader?.close()
imageReader = null
previewImageReader?.close()
previewImageReader = null
previewSurface = null
previewRequestBuilder = null
//清理所有缓存的相机特性和属性
cachedCharacteristics = null
cachedSensorOrientation = 0
cachedLensFacing = CameraCharacteristics.LENS_FACING_BACK
cachedHardwareLevel = CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED
_state.value = _state.value.copy(isPreviewActive = false)
Log.d(TAG, "Camera closed")
PLog.d(TAG, "Camera closed")
} catch (e: Exception) {
Log.e(TAG, "Error closing camera", e)
PLog.e(TAG, "Error closing camera", e)
}
}
@@ -8,6 +8,7 @@ import android.hardware.camera2.CameraMetadata
import android.os.Build
import android.util.Log
import android.util.Range
import com.hinnka.mycamera.utils.PLog
/**
* 相机发现器
@@ -53,7 +54,7 @@ class CameraDiscovery(private val context: Context) {
// 获取完整的 Camera ID 列表(包括探测的隐藏摄像头)
val allCameraIds = getAllCameraIds()
Log.d(TAG, "Camera2 discovered IDs: $allCameraIds")
PLog.d(TAG, "Camera2 discovered IDs: $allCameraIds")
// 构建摄像头信息
val backCameras = mutableListOf<CameraInfoWithZoom>()
@@ -83,10 +84,10 @@ class CameraDiscovery(private val context: Context) {
}
}
Log.d(TAG, "Camera2: $cameraId: facing=$lensFacing, intrinsicZoom=$intrinsicZoomRatio")
PLog.d(TAG, "Camera2: $cameraId: facing=$lensFacing, intrinsicZoom=$intrinsicZoomRatio")
} catch (e: Exception) {
Log.w(TAG, "Failed to get camera $cameraId info", e)
PLog.w(TAG, "Failed to get camera $cameraId info", e)
}
}
@@ -97,9 +98,9 @@ class CameraDiscovery(private val context: Context) {
// 添加前置摄像头
frontCamera?.let { cameras.add(it) }
Log.d(TAG, "Camera2 final list:")
PLog.d(TAG, "Camera2 final list:")
cameras.forEach { cam ->
Log.d(TAG, " - ${cam.cameraId}: ${cam.lensType}, intrinsicZoom=${cam.intrinsicZoomRatio}")
PLog.d(TAG, " - ${cam.cameraId}: ${cam.lensType}, intrinsicZoom=${cam.intrinsicZoomRatio}")
}
return cameras
@@ -115,14 +116,14 @@ class CameraDiscovery(private val context: Context) {
val systemCameraIds = try {
cameraManager.cameraIdList.toList()
} catch (e: CameraAccessException) {
Log.e(TAG, "Failed to get camera ID list (CameraAccessException)", e)
PLog.e(TAG, "Failed to get camera ID list (CameraAccessException)", e)
emptyList()
} catch (e: Exception) {
Log.e(TAG, "Failed to get camera ID list (${e.javaClass.simpleName}): ${e.message}", e)
PLog.e(TAG, "Failed to get camera ID list (${e.javaClass.simpleName}): ${e.message}", e)
emptyList()
}
Log.d(TAG, "System camera IDs: $systemCameraIds")
PLog.d(TAG, "System camera IDs: $systemCameraIds")
// 如果系统已经返回了足够多的摄像头,或者需要跳过探测,直接返回
if (systemCameraIds.size > 2 || shouldSkipProbing()) {
@@ -134,7 +135,7 @@ class CameraDiscovery(private val context: Context) {
val probedIds = probeCameraIds(systemCameraIds)
val allIds = (systemCameraIds + probedIds).distinct()
Log.d(TAG, "After probing: $allIds (probed: $probedIds)")
PLog.d(TAG, "After probing: $allIds (probed: $probedIds)")
cachedCameraIds = allIds
return allIds
@@ -149,7 +150,7 @@ class CameraDiscovery(private val context: Context) {
// Huawei / Honor 跳过
if (SKIP_PROBE_MANUFACTURERS.any { manufacturer.contains(it) }) {
Log.d(TAG, "Skipping probe for manufacturer: $manufacturer")
PLog.d(TAG, "Skipping probe for manufacturer: $manufacturer")
return true
}
@@ -157,13 +158,13 @@ class CameraDiscovery(private val context: Context) {
if (manufacturer.contains("vivo")) {
// Android 10 及以下跳过
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) {
Log.d(TAG, "Skipping probe for Vivo on Android ${Build.VERSION.SDK_INT}")
PLog.d(TAG, "Skipping probe for Vivo on Android ${Build.VERSION.SDK_INT}")
return true
}
// 特定机型跳过
if (VIVO_SKIP_MODELS.contains(Build.MODEL)) {
Log.d(TAG, "Skipping probe for Vivo model: ${Build.MODEL}")
PLog.d(TAG, "Skipping probe for Vivo model: ${Build.MODEL}")
return true
}
}
@@ -196,15 +197,15 @@ class CameraDiscovery(private val context: Context) {
// 只有 intrinsicZoomRatio != 1.0 的才是广角/长焦
if (intrinsicZoomRatio != 1f) {
Log.d(TAG, "Probed camera $cameraId: intrinsicZoom=$intrinsicZoomRatio")
PLog.d(TAG, "Probed camera $cameraId: intrinsicZoom=$intrinsicZoomRatio")
foundIds.add(cameraId)
} else {
Log.d(TAG, "Probed camera $cameraId: skipped (intrinsicZoom=1.0)")
PLog.d(TAG, "Probed camera $cameraId: skipped (intrinsicZoom=1.0)")
}
}
} catch (e: Exception) {
// 该 ID 不存在或无法访问,忽略
Log.v(TAG, "Probe camera $cameraId failed: ${e.message}")
PLog.v(TAG, "Probe camera $cameraId failed: ${e.message}")
}
}
@@ -236,7 +237,7 @@ class CameraDiscovery(private val context: Context) {
return current35mm / default35mm
} catch (e: Exception) {
Log.w(TAG, "Failed to calculate intrinsicZoomRatio for camera $cameraId", e)
PLog.w(TAG, "Failed to calculate intrinsicZoomRatio for camera $cameraId", e)
return 1f
}
}
@@ -255,7 +256,7 @@ class CameraDiscovery(private val context: Context) {
return get35mmEquivalentFocalLength(characteristics)
}
} catch (e: Exception) {
Log.w(TAG, "Failed to get default focal length", e)
PLog.w(TAG, "Failed to get default focal length", e)
}
return 0f
@@ -302,7 +303,7 @@ class CameraDiscovery(private val context: Context) {
// 专用微距镜头的典型特征:
// (1) 最小对焦距离很大
if (minFocusDistance >= 30f) {
Log.d(TAG, "isMacroLens: minFocusDistance=$minFocusDistance, focusCalibration=$focusCalibration")
PLog.d(TAG, "isMacroLens: minFocusDistance=$minFocusDistance, focusCalibration=$focusCalibration")
return true
}
return false
@@ -363,32 +364,35 @@ class CameraDiscovery(private val context: Context) {
// 焦距信息
val focalLengths = characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)
val focalLength = focalLengths?.firstOrNull() ?: 0f
// 计算 35mm 等效焦距
val focalLength35mm = get35mmEquivalentFocalLength(characteristics)
// ISO 范围
val isoRange = characteristics.get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE)
// 曝光时间范围
val exposureTimeRange = characteristics.get(CameraCharacteristics.SENSOR_INFO_EXPOSURE_TIME_RANGE)
// 曝光补偿范围
val exposureCompensationRange = characteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE)
?: Range(0, 0)
// 曝光补偿步长
val exposureCompensationStep = characteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP)?.toFloat() ?: 0f
// 最大数字变焦
val maxZoom = characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM) ?: 1f
// 传感器方向
val sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0
// 活动区域大小
val activeArraySize = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE)
// 硬件支持级别
val hardwareLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL) ?: -1
return CameraInfo(
cameraId = cameraId,
lensFacing = lensFacing,
@@ -405,7 +409,8 @@ class CameraDiscovery(private val context: Context) {
focalLength = focalLength,
focalLength35mmEquivalent = focalLength35mm,
zoomSteps = listOf(1f),
intrinsicZoomRatio = intrinsicZoomRatio
intrinsicZoomRatio = intrinsicZoomRatio,
hardwareLevel = hardwareLevel
)
}
@@ -56,7 +56,8 @@ data class CameraInfo(
val focalLength: Float = 0f, // 物理焦距 (mm)
val focalLength35mmEquivalent: Float = 0f, // 35mm等效焦距
val zoomSteps: List<Float> = listOf(1f), // 可用的变焦档位 (如 [0.5, 1.0, 2.0])
val intrinsicZoomRatio: Float = 1f // 固有变焦比例 (CameraX 1.3.0+)
val intrinsicZoomRatio: Float = 1f, // 固有变焦比例 (CameraX 1.3.0+)
val hardwareLevel: Int = -1 // 硬件支持级别
) {
/**
* 获取镜头类型显示名称
@@ -80,6 +81,20 @@ data class CameraInfo(
* 是否支持长焦(maxZoom > 2)
*/
fun hasTelephoto(): Boolean = maxZoom > 2f
/**
* 获取硬件支持级别的可读名称
*/
fun getHardwareLevelName(): String {
return when (hardwareLevel) {
0 -> "LIMITED"
1 -> "FULL"
2 -> "LEGACY"
3 -> "LEVEL_3"
4 -> "EXTERNAL"
else -> "UNKNOWN"
}
}
}
/**
@@ -7,6 +7,7 @@ import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.util.Log
import android.util.Size
import com.hinnka.mycamera.utils.PLog
import kotlin.math.abs
/**
@@ -50,7 +51,7 @@ object CameraUtils {
// 如果没有比例完全匹配的,则选择高度 >= 1080 中最小的一个(之前的逻辑)
return previewSizes.filter { it.height >= 1080 }.minByOrNull { it.width } ?: Size(1440, 1080)
} catch (e: Exception) {
Log.d("CameraUtils", "getFixedPreviewSize: ${e.message}")
PLog.d("CameraUtils", "getFixedPreviewSize: ${e.message}")
return Size(1440, 1080)
}
}
@@ -79,7 +80,7 @@ object CameraUtils {
// 选择最大的尺寸
sizes.maxByOrNull { it.width * it.height } ?: Size(1920, 1080)
} catch (e: Exception) {
// Log.e(TAG, "Failed to get capture size", e)
// PLog.e(TAG, "Failed to get capture size", e)
Size(1920, 1080)
}
}
@@ -5,6 +5,7 @@ import android.hardware.camera2.CameraCharacteristics
import android.os.Build
import android.util.Log
import android.util.Size
import com.hinnka.mycamera.utils.PLog
/**
* 高分辨率拍照能力检测工具
@@ -157,7 +158,7 @@ object HighResolutionHelper {
addIfValid(size, format, minPixels, configs, seen)
}
} catch (e: Exception) {
Log.w(TAG, "Error getting output sizes for format $format: ${e.message}")
PLog.w(TAG, "Error getting output sizes for format $format: ${e.message}")
}
}
}
@@ -177,7 +178,7 @@ object HighResolutionHelper {
try {
val value = getVendorKeyValue(characteristics, keyName) ?: continue
parseVendorStreamConfigurations(value, minPixels, configs, seen)
Log.d(TAG, "Found vendor key: $keyName with ${value.size} values")
PLog.d(TAG, "Found vendor key: $keyName with ${value.size} values")
} catch (e: Exception) {
// 私有 Key 不存在或无法访问,静默忽略
}
@@ -363,18 +364,18 @@ object HighResolutionHelper {
fun logResolutionCapabilities(characteristics: CameraCharacteristics) {
val options = getMegapixelOptions(characteristics)
Log.i(TAG, "========== High Resolution Capabilities ==========")
Log.i(TAG, "Max Megapixels: ${options.maxMegapixels}MP")
Log.i(TAG, "Max Resolution: ${options.maxResolution}")
Log.i(TAG, "12MP: ${options.mp12}")
Log.i(TAG, "24MP: ${options.mp24}")
Log.i(TAG, "48MP: ${options.mp48}")
Log.i(TAG, "108MP: ${options.mp108}")
Log.i(TAG, "200MP: ${options.mp200}")
Log.i(TAG, "All resolutions (${options.allResolutions.size}):")
PLog.i(TAG, "========== High Resolution Capabilities ==========")
PLog.i(TAG, "Max Megapixels: ${options.maxMegapixels}MP")
PLog.i(TAG, "Max Resolution: ${options.maxResolution}")
PLog.i(TAG, "12MP: ${options.mp12}")
PLog.i(TAG, "24MP: ${options.mp24}")
PLog.i(TAG, "48MP: ${options.mp48}")
PLog.i(TAG, "108MP: ${options.mp108}")
PLog.i(TAG, "200MP: ${options.mp200}")
PLog.i(TAG, "All resolutions (${options.allResolutions.size}):")
options.allResolutions.forEach { config ->
Log.i(TAG, " - $config")
PLog.i(TAG, " - $config")
}
Log.i(TAG, "===================================================")
PLog.i(TAG, "===================================================")
}
}
@@ -5,6 +5,7 @@ import android.net.Uri
import android.util.Log
import com.hinnka.mycamera.lut.LutConverter
import com.hinnka.mycamera.lut.LutInfo
import com.hinnka.mycamera.utils.PLog
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
@@ -70,10 +71,10 @@ class CustomImportManager(private val context: Context) {
// 保存到配置文件
saveLutToConfig(lutId, name, plutFileName)
Log.d(TAG, "LUT imported successfully: $lutId ($name)")
PLog.d(TAG, "LUT imported successfully: $lutId ($name)")
lutId
} catch (e: Exception) {
Log.e(TAG, "Failed to import LUT", e)
PLog.e(TAG, "Failed to import LUT", e)
null
}
}
@@ -110,10 +111,10 @@ class CustomImportManager(private val context: Context) {
// 保存到配置文件
saveFrameToConfig(frameId, nameMap, "$frameId.json")
Log.d(TAG, "Frame imported successfully: $frameId")
PLog.d(TAG, "Frame imported successfully: $frameId")
frameId
} catch (e: Exception) {
Log.e(TAG, "Failed to import frame", e)
PLog.e(TAG, "Failed to import frame", e)
null
}
}
@@ -163,7 +164,7 @@ class CustomImportManager(private val context: Context) {
lutList
} catch (e: Exception) {
Log.e(TAG, "Failed to load custom LUTs", e)
PLog.e(TAG, "Failed to load custom LUTs", e)
emptyList()
}
}
@@ -204,7 +205,7 @@ class CustomImportManager(private val context: Context) {
frameList
} catch (e: Exception) {
Log.e(TAG, "Failed to load custom frames", e)
PLog.e(TAG, "Failed to load custom frames", e)
emptyList()
}
}
@@ -241,7 +242,7 @@ class CustomImportManager(private val context: Context) {
true
} catch (e: Exception) {
Log.e(TAG, "Failed to delete custom LUT", e)
PLog.e(TAG, "Failed to delete custom LUT", e)
false
}
}
@@ -277,7 +278,7 @@ class CustomImportManager(private val context: Context) {
true
} catch (e: Exception) {
Log.e(TAG, "Failed to delete custom frame", e)
PLog.e(TAG, "Failed to delete custom frame", e)
false
}
}
@@ -3,6 +3,7 @@ package com.hinnka.mycamera.frame
import android.content.Context
import android.util.Log
import android.util.LruCache
import com.hinnka.mycamera.utils.PLog
/**
* 边框管理器
@@ -27,7 +28,7 @@ class FrameManager(private val context: Context) {
*/
fun initialize() {
availableFrames = FrameTemplateParser.listAvailableFrames(context)
Log.d(TAG, "Found ${availableFrames.size} frame templates")
PLog.d(TAG, "Found ${availableFrames.size} frame templates")
}
/**
@@ -51,13 +52,13 @@ class FrameManager(private val context: Context) {
fun loadTemplate(id: String): FrameTemplate? {
// 先从缓存查找
templateCache.get(id)?.let {
Log.d(TAG, "Frame template loaded from cache: $id")
PLog.d(TAG, "Frame template loaded from cache: $id")
return it
}
// 查找边框信息
val frameInfo = getFrameInfo(id) ?: run {
Log.e(TAG, "Frame not found: $id")
PLog.e(TAG, "Frame not found: $id")
return null
}
@@ -67,11 +68,11 @@ class FrameManager(private val context: Context) {
if (template != null) {
templateCache.put(id, template)
Log.d(TAG, "Frame template loaded: $id")
PLog.d(TAG, "Frame template loaded: $id")
}
template
} catch (e: Exception) {
Log.e(TAG, "Failed to load frame template: $id", e)
PLog.e(TAG, "Failed to load frame template: $id", e)
null
}
}
@@ -101,7 +102,7 @@ class FrameManager(private val context: Context) {
*/
fun clearCache() {
templateCache.evictAll()
Log.d(TAG, "Frame template cache cleared")
PLog.d(TAG, "Frame template cache cleared")
}
/**
@@ -10,6 +10,7 @@ import com.hinnka.mycamera.gallery.PhotoMetadata
import java.text.SimpleDateFormat
import java.util.*
import androidx.core.graphics.createBitmap
import com.hinnka.mycamera.utils.PLog
/**
@@ -47,7 +48,7 @@ class FrameRenderer(private val context: Context) {
showAppBranding: Boolean = true,
): Bitmap {
Log.d(TAG, "render: $metadata")
PLog.d(TAG, "render: $metadata")
val layout = template.layout
@@ -528,7 +529,7 @@ class FrameRenderer(private val context: Context) {
size to size
}
} catch (e: Exception) {
Log.e(TAG, "Failed to draw logo", e)
PLog.e(TAG, "Failed to draw logo", e)
return 0 to 0
}
}
@@ -572,7 +573,7 @@ class FrameRenderer(private val context: Context) {
return bmpW + margin * 2
} catch (e: Exception) {
Log.e(TAG, "Failed to draw logo", e)
PLog.e(TAG, "Failed to draw logo", e)
return 0f
}
}
@@ -3,6 +3,7 @@ package com.hinnka.mycamera.frame
import android.content.Context
import android.graphics.Color
import android.util.Log
import com.hinnka.mycamera.utils.PLog
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedReader
@@ -40,7 +41,7 @@ object FrameTemplateParser {
}
}
} catch (e: Exception) {
Log.e(TAG, "Failed to list frame templates", e)
PLog.e(TAG, "Failed to list frame templates", e)
}
return frames
@@ -88,7 +89,7 @@ object FrameTemplateParser {
val json = readAssetFile(context, path)
parseTemplate(json)
} catch (e: Exception) {
Log.e(TAG, "Failed to parse frame template: $frameId", e)
PLog.e(TAG, "Failed to parse frame template: $frameId", e)
null
}
}
@@ -3,6 +3,7 @@ package com.hinnka.mycamera.gallery
import android.util.Log
import androidx.exifinterface.media.ExifInterface
import com.hinnka.mycamera.camera.CaptureInfo
import com.hinnka.mycamera.utils.PLog
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
@@ -121,13 +122,13 @@ object ExifWriter {
// 保存
exif.saveAttributes()
Log.d(TAG, "EXIF written to ${file.name}: ISO=${captureInfo.iso}, " +
PLog.d(TAG, "EXIF written to ${file.name}: ISO=${captureInfo.iso}, " +
"Exposure=${captureInfo.formatExposureTime()}, " +
"Aperture=${captureInfo.formatAperture()}, " +
"Focal=${captureInfo.formatFocalLength()}")
} catch (e: Exception) {
Log.e(TAG, "Failed to write EXIF to ${file.name}", e)
PLog.e(TAG, "Failed to write EXIF to ${file.name}", e)
}
}
@@ -7,6 +7,7 @@ import android.media.ThumbnailUtils
import android.net.Uri
import android.util.Log
import com.hinnka.mycamera.camera.CaptureInfo
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
@@ -141,10 +142,10 @@ object PhotoManager {
thumbnailJob.await()
}
Log.d(TAG, "Photo saved: $photoId")
PLog.d(TAG, "Photo saved: $photoId")
photoId
} catch (e: Exception) {
Log.e(TAG, "Failed to save photo", e)
PLog.e(TAG, "Failed to save photo", e)
null
}
}
@@ -167,7 +168,7 @@ object PhotoManager {
}
}
} catch (e: Exception) {
Log.e(TAG, "Failed to save thumbnail from source", e)
PLog.e(TAG, "Failed to save thumbnail from source", e)
}
}
@@ -197,7 +198,7 @@ object PhotoManager {
thumbnail.recycle()
}
} catch (e: Exception) {
Log.e(TAG, "Failed to generate thumbnail", e)
PLog.e(TAG, "Failed to generate thumbnail", e)
}
}
@@ -239,7 +240,7 @@ object PhotoManager {
}
true
} catch (e: Exception) {
Log.e(TAG, "Failed to delete photo: $photoId", e)
PLog.e(TAG, "Failed to delete photo: $photoId", e)
false
}
}
@@ -258,7 +259,7 @@ object PhotoManager {
null
}
} catch (e: Exception) {
Log.e(TAG, "Failed to load metadata for photo: $photoId", e)
PLog.e(TAG, "Failed to load metadata for photo: $photoId", e)
null
}
}
@@ -274,7 +275,7 @@ object PhotoManager {
file.writeText(metadata.toJson())
true
} catch (e: Exception) {
Log.e(TAG, "Failed to save metadata for photo: $photoId", e)
PLog.e(TAG, "Failed to save metadata for photo: $photoId", e)
false
}
}
@@ -308,10 +309,10 @@ object PhotoManager {
savePreviewFileIfNeed(photoFile, previewFile)
generateThumbnail(photoFile, thumbnailFile)
Log.d(TAG, "Photo imported: $photoId")
PLog.d(TAG, "Photo imported: $photoId")
photoId
} catch (e: Exception) {
Log.e(TAG, "Failed to import photo", e)
PLog.e(TAG, "Failed to import photo", e)
null
}
}
@@ -5,6 +5,7 @@ import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.exifinterface.media.ExifInterface
import com.hinnka.mycamera.utils.PLog
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*
@@ -100,7 +101,7 @@ data class PhotoMetadata(
isImported = obj.optBoolean("isImported", false)
)
} catch (e: Exception) {
Log.e(TAG, "Failed to parse JSON", e)
PLog.e(TAG, "Failed to parse JSON", e)
null
}
}
@@ -181,7 +182,7 @@ data class PhotoMetadata(
)
} ?: createDefault(0, 0)
} catch (e: Exception) {
Log.e(TAG, "Failed to load EXIF from $uri", e)
PLog.e(TAG, "Failed to load EXIF from $uri", e)
createDefault(0, 0)
}
}
@@ -2,6 +2,7 @@ package com.hinnka.mycamera.lut
import android.content.Context
import android.util.Log
import com.hinnka.mycamera.utils.PLog
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
@@ -90,7 +91,7 @@ object CubeLutParser {
val expectedDataSize = size * size * size * 3
if (dataList.size != expectedDataSize) {
Log.w(TAG, "Data size mismatch: expected $expectedDataSize, got ${dataList.size}")
PLog.w(TAG, "Data size mismatch: expected $expectedDataSize, got ${dataList.size}")
}
return LutConfig(
@@ -137,7 +138,7 @@ object CubeLutParser {
)
}
} catch (e: Exception) {
Log.e(TAG, "Failed to list LUT files", e)
PLog.e(TAG, "Failed to list LUT files", e)
emptyList()
}
}
@@ -3,6 +3,7 @@ package com.hinnka.mycamera.lut
import android.opengl.GLES11Ext
import android.opengl.GLES30
import android.util.Log
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
@@ -24,7 +25,7 @@ object GlUtils {
fun compileShader(type: Int, source: String): Int {
val shader = GLES30.glCreateShader(type)
if (shader == 0) {
Log.e(TAG, "Failed to create shader")
PLog.e(TAG, "Failed to create shader")
return 0
}
@@ -36,7 +37,7 @@ object GlUtils {
if (compileStatus[0] == 0) {
val errorLog = GLES30.glGetShaderInfoLog(shader)
Log.e(TAG, "Shader compilation failed: $errorLog")
PLog.e(TAG, "Shader compilation failed: $errorLog")
GLES30.glDeleteShader(shader)
return 0
}
@@ -54,7 +55,7 @@ object GlUtils {
fun linkProgram(vertexShader: Int, fragmentShader: Int): Int {
val program = GLES30.glCreateProgram()
if (program == 0) {
Log.e(TAG, "Failed to create program")
PLog.e(TAG, "Failed to create program")
return 0
}
@@ -67,7 +68,7 @@ object GlUtils {
if (linkStatus[0] == 0) {
val errorLog = GLES30.glGetProgramInfoLog(program)
Log.e(TAG, "Program linking failed: $errorLog")
PLog.e(TAG, "Program linking failed: $errorLog")
GLES30.glDeleteProgram(program)
return 0
}
@@ -87,7 +88,7 @@ object GlUtils {
val textureId = textureIds[0]
if (textureId == 0) {
Log.e(TAG, "Failed to generate 3D texture")
PLog.e(TAG, "Failed to generate 3D texture")
return 0
}
@@ -125,7 +126,7 @@ object GlUtils {
GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, 0)
checkGlError("create3DTexture")
// Log.d(TAG, "Created 3D LUT texture: size=${lutConfig.size}, id=$textureId")
// PLog.d(TAG, "Created 3D LUT texture: size=${lutConfig.size}, id=$textureId")
return textureId
}
@@ -141,7 +142,7 @@ object GlUtils {
val textureId = textureIds[0]
if (textureId == 0) {
Log.e(TAG, "Failed to generate OES texture")
PLog.e(TAG, "Failed to generate OES texture")
return 0
}
@@ -221,7 +222,7 @@ object GlUtils {
fun checkGlError(tag: String) {
var error: Int
while (GLES30.glGetError().also { error = it } != GLES30.GL_NO_ERROR) {
Log.e(TAG, "$tag: glError $error")
PLog.e(TAG, "$tag: glError $error")
}
}
}
@@ -8,6 +8,7 @@ import android.opengl.EGLDisplay
import android.opengl.EGLSurface
import android.opengl.GLES30
import android.util.Log
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.withContext
import java.nio.ByteBuffer
@@ -63,14 +64,14 @@ class LutImageProcessor {
// 获取 EGL Display
eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)
if (eglDisplay == EGL14.EGL_NO_DISPLAY) {
Log.e(TAG, "Unable to get EGL display")
PLog.e(TAG, "Unable to get EGL display")
return false
}
// 初始化 EGL
val version = IntArray(2)
if (!EGL14.eglInitialize(eglDisplay, version, 0, version, 1)) {
Log.e(TAG, "Unable to initialize EGL")
PLog.e(TAG, "Unable to initialize EGL")
return false
}
@@ -88,7 +89,7 @@ class LutImageProcessor {
val configs = arrayOfNulls<EGLConfig>(1)
val numConfigs = IntArray(1)
if (!EGL14.eglChooseConfig(eglDisplay, configAttribs, 0, configs, 0, 1, numConfigs, 0)) {
Log.e(TAG, "Unable to choose EGL config")
PLog.e(TAG, "Unable to choose EGL config")
return false
}
@@ -101,7 +102,7 @@ class LutImageProcessor {
)
eglContext = EGL14.eglCreateContext(eglDisplay, config, EGL14.EGL_NO_CONTEXT, contextAttribs, 0)
if (eglContext == EGL14.EGL_NO_CONTEXT) {
Log.e(TAG, "Unable to create EGL context")
PLog.e(TAG, "Unable to create EGL context")
return false
}
@@ -113,13 +114,13 @@ class LutImageProcessor {
)
eglSurface = EGL14.eglCreatePbufferSurface(eglDisplay, config, surfaceAttribs, 0)
if (eglSurface == EGL14.EGL_NO_SURFACE) {
Log.e(TAG, "Unable to create EGL surface")
PLog.e(TAG, "Unable to create EGL surface")
return false
}
// 激活上下文
if (!EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) {
Log.e(TAG, "Unable to make EGL current")
PLog.e(TAG, "Unable to make EGL current")
return false
}
@@ -128,11 +129,11 @@ class LutImageProcessor {
initBuffers()
isInitialized = true
Log.d(TAG, "LutImageProcessor initialized")
PLog.d(TAG, "LutImageProcessor initialized")
return true
} catch (e: Exception) {
Log.e(TAG, "Failed to initialize", e)
PLog.e(TAG, "Failed to initialize", e)
return false
}
}
@@ -265,7 +266,7 @@ class LutImageProcessor {
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) {
Log.e(TAG, "Framebuffer not complete: $status")
PLog.e(TAG, "Framebuffer not complete: $status")
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
@@ -343,7 +344,7 @@ class LutImageProcessor {
GLES30.glGetShaderiv(shader, GLES30.GL_COMPILE_STATUS, compiled, 0)
if (compiled[0] == 0) {
val error = GLES30.glGetShaderInfoLog(shader)
Log.e(TAG, "Shader compilation failed: $error")
PLog.e(TAG, "Shader compilation failed: $error")
GLES30.glDeleteShader(shader)
return 0
}
@@ -412,7 +413,7 @@ class LutImageProcessor {
EGL14.eglTerminate(eglDisplay)
isInitialized = false
Log.d(TAG, "LutImageProcessor released")
PLog.d(TAG, "LutImageProcessor released")
}
companion object {
@@ -4,6 +4,7 @@ import android.content.Context
import android.util.Log
import android.util.LruCache
import com.hinnka.mycamera.data.CustomImportManager
import com.hinnka.mycamera.utils.PLog
/**
* LUT 管理器
@@ -41,7 +42,7 @@ class LutManager(private val context: Context) {
// 将自定义 LUT 放在最前面
availableLuts = customLuts + builtInLuts
Log.d(TAG, "Found ${availableLuts.size} LUT files (${customLuts.size} custom, ${builtInLuts.size} built-in)")
PLog.d(TAG, "Found ${availableLuts.size} LUT files (${customLuts.size} custom, ${builtInLuts.size} built-in)")
}
/**
@@ -65,13 +66,13 @@ class LutManager(private val context: Context) {
fun loadLut(id: String): LutConfig? {
// 先从缓存查找
lutCache.get(id)?.let {
Log.d(TAG, "LUT loaded from cache: $id")
PLog.d(TAG, "LUT loaded from cache: $id")
return it
}
// 查找 LUT 信息
val lutInfo = getLutInfo(id) ?: run {
Log.e(TAG, "LUT not found: $id")
PLog.e(TAG, "LUT not found: $id")
return null
}
@@ -90,14 +91,14 @@ class LutManager(private val context: Context) {
if (lutConfig.isValid()) {
// 添加到缓存
lutCache.put(id, lutConfig)
Log.d(TAG, "LUT loaded: $id, size: ${lutConfig.size}")
PLog.d(TAG, "LUT loaded: $id, size: ${lutConfig.size}")
lutConfig
} else {
Log.e(TAG, "Invalid LUT data: $id")
PLog.e(TAG, "Invalid LUT data: $id")
null
}
} catch (e: Exception) {
Log.e(TAG, "Failed to load LUT: $id", e)
PLog.e(TAG, "Failed to load LUT: $id", e)
null
}
}
@@ -135,7 +136,7 @@ class LutManager(private val context: Context) {
*/
fun clearCache() {
lutCache.evictAll()
Log.d(TAG, "LUT cache cleared")
PLog.d(TAG, "LUT cache cleared")
}
/**
@@ -2,6 +2,7 @@ package com.hinnka.mycamera.lut
import android.content.Context
import android.util.Log
import com.hinnka.mycamera.utils.PLog
import org.json.JSONObject
import java.io.InputStream
import java.nio.ByteBuffer
@@ -124,10 +125,10 @@ object LutParser {
)
}
Log.d(TAG, "Loaded ${lutList.size} LUTs from config.json")
PLog.d(TAG, "Loaded ${lutList.size} LUTs from config.json")
lutList
} catch (e: Exception) {
Log.e(TAG, "Failed to load LUT config", e)
PLog.e(TAG, "Failed to load LUT config", e)
emptyList()
}
}
@@ -7,6 +7,7 @@ import android.opengl.GLES30
import android.opengl.GLSurfaceView
import android.opengl.Matrix
import android.util.Log
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.ShortBuffer
@@ -102,7 +103,7 @@ class LutRenderer : GLSurfaceView.Renderer {
* Surface 创建时调用
*/
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
Log.d(TAG, "onSurfaceCreated")
PLog.d(TAG, "onSurfaceCreated")
// 设置清屏颜色
GLES30.glClearColor(0f, 0f, 0f, 1f)
@@ -142,7 +143,7 @@ class LutRenderer : GLSurfaceView.Renderer {
* Surface 尺寸变化时调用
*/
override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
Log.d(TAG, "onSurfaceChanged: ${width}x${height}")
PLog.d(TAG, "onSurfaceChanged: ${width}x${height}")
viewportWidth = width
viewportHeight = height
@@ -257,7 +258,7 @@ class LutRenderer : GLSurfaceView.Renderer {
val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, Shaders.FRAGMENT_SHADER_LUT)
if (vertexShader == 0 || fragmentShader == 0) {
Log.e(TAG, "Failed to compile shaders")
PLog.e(TAG, "Failed to compile shaders")
return
}
@@ -268,7 +269,7 @@ class LutRenderer : GLSurfaceView.Renderer {
GLES30.glDeleteShader(fragmentShader)
if (programId == 0) {
Log.e(TAG, "Failed to link program")
PLog.e(TAG, "Failed to link program")
return
}
@@ -285,7 +286,7 @@ class LutRenderer : GLSurfaceView.Renderer {
aPositionLocation = GLES30.glGetAttribLocation(programId, "aPosition")
aTexCoordLocation = GLES30.glGetAttribLocation(programId, "aTexCoord")
// Log.d(TAG, "Shader program created: $programId")
// PLog.d(TAG, "Shader program created: $programId")
}
/**
@@ -357,7 +358,7 @@ class LutRenderer : GLSurfaceView.Renderer {
lutTextureId = GlUtils.create3DTexture(lutConfig)
lutSize = lutConfig.size.toFloat()
lutEnabled = true
// Log.d(TAG, "LUT set: ${lutConfig.title}, size: ${lutConfig.size}")
// PLog.d(TAG, "LUT set: ${lutConfig.title}, size: ${lutConfig.size}")
} else {
lutEnabled = false
}
@@ -410,7 +411,7 @@ class LutRenderer : GLSurfaceView.Renderer {
Matrix.scaleM(mvpMatrix, 0, scaleX, scaleY, 1f)
}
Log.d(TAG, "MVP matrix updated: viewport=${viewportWidth}x${viewportHeight}, preview=${previewWidth}x${previewHeight}")
PLog.d(TAG, "MVP matrix updated: viewport=${viewportWidth}x${viewportHeight}, preview=${previewWidth}x${previewHeight}")
}
/**
@@ -464,7 +465,7 @@ class LutRenderer : GLSurfaceView.Renderer {
onPreviewFrameCaptured?.invoke(scaledBitmap)
} catch (e: Exception) {
Log.e(TAG, "Failed to capture preview frame", e)
PLog.e(TAG, "Failed to capture preview frame", e)
}
}
@@ -9,6 +9,7 @@ import android.util.Log
import android.view.Surface
import com.hinnka.mycamera.lut.LutConfig
import com.hinnka.mycamera.lut.LutRenderer
import com.hinnka.mycamera.utils.PLog
/**
* 相机预览 GLSurfaceView
@@ -60,7 +61,7 @@ class CameraGLSurfaceView @JvmOverloads constructor(
// 保持 EGL 上下文
preserveEGLContextOnPause = true
Log.d(TAG, "CameraGLSurfaceView initialized")
PLog.d(TAG, "CameraGLSurfaceView initialized")
}
/**
@@ -143,17 +144,17 @@ class CameraGLSurfaceView @JvmOverloads constructor(
override fun onPause() {
super.onPause()
Log.d(TAG, "onPause")
PLog.d(TAG, "onPause")
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume")
PLog.d(TAG, "onResume")
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
Log.d(TAG, "onDetachedFromWindow")
PLog.d(TAG, "onDetachedFromWindow")
// 通知 Surface 销毁
onSurfaceDestroyed?.invoke()
@@ -0,0 +1,235 @@
package com.hinnka.mycamera.ui.components
import android.os.Build
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import com.hinnka.mycamera.camera.CameraInfo
@Composable
fun CameraInfoDialog(
cameras: List<CameraInfo>,
onDismiss: () -> Unit
) {
Dialog(onDismissRequest = onDismiss) {
Card(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.8f)
.padding(16.dp),
shape = RoundedCornerShape(24.dp),
colors = CardDefaults.cardColors(containerColor = Color(0xFF1A1A1A))
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(
Brush.verticalGradient(
listOf(Color(0xFF2C2C2C), Color(0xFF1A1A1A))
)
)
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(24.dp)
) {
// 标题
Text(
text = "摄像头信息",
color = Color.White,
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(bottom = 8.dp)
)
Text(
text = "设备: ${Build.MANUFACTURER} ${Build.MODEL}",
color = Color.Gray,
fontSize = 14.sp,
modifier = Modifier.padding(bottom = 16.dp)
)
Divider(color = Color.DarkGray, thickness = 1.dp)
Spacer(modifier = Modifier.height(16.dp))
// 摄像头列表
Column(
modifier = Modifier
.weight(1f)
.verticalScroll(rememberScrollState())
) {
cameras.forEachIndexed { index, camera ->
CameraInfoItem(camera)
if (index < cameras.size - 1) {
Spacer(modifier = Modifier.height(16.dp))
Divider(color = Color.DarkGray.copy(alpha = 0.5f), thickness = 0.5.dp)
Spacer(modifier = Modifier.height(16.dp))
}
}
}
Spacer(modifier = Modifier.height(16.dp))
// 关闭按钮
Button(
onClick = onDismiss,
modifier = Modifier
.fillMaxWidth()
.height(48.dp),
shape = RoundedCornerShape(24.dp),
colors = ButtonDefaults.buttonColors(
containerColor = Color(0xFF3A3A3A),
contentColor = Color.White
)
) {
Text(text = "关闭", fontSize = 16.sp)
}
}
}
}
}
}
@Composable
private fun CameraInfoItem(camera: CameraInfo) {
Column(
modifier = Modifier.fillMaxWidth()
) {
// 摄像头名称
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
) {
Text(
text = camera.getLensDisplayName(),
color = Color.White,
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "ID: ${camera.cameraId}",
color = Color.Gray,
fontSize = 12.sp,
fontFamily = FontFamily.Monospace
)
}
Spacer(modifier = Modifier.height(12.dp))
// 硬件支持级别 - 突出显示
InfoRow(
label = "硬件级别",
value = camera.getHardwareLevelName(),
highlight = true
)
// 其他详细信息
InfoRow(
label = "传感器方向",
value = "${camera.sensorOrientation}°"
)
InfoRow(
label = "物理焦距",
value = if (camera.focalLength > 0) "${String.format("%.2f", camera.focalLength)}mm" else "N/A"
)
InfoRow(
label = "等效焦距",
value = if (camera.focalLength35mmEquivalent > 0) "${String.format("%.1f", camera.focalLength35mmEquivalent)}mm" else "N/A"
)
InfoRow(
label = "固有变焦比",
value = String.format("%.2fx", camera.intrinsicZoomRatio)
)
InfoRow(
label = "数字变焦范围",
value = "1.0x - ${String.format("%.1f", camera.maxZoom)}x"
)
camera.isoRange?.let { range ->
InfoRow(
label = "ISO 范围",
value = "${range.lower} - ${range.upper}"
)
}
camera.exposureTimeRange?.let { range ->
InfoRow(
label = "曝光时间范围",
value = "${formatExposureTime(range.lower)} - ${formatExposureTime(range.upper)}"
)
}
InfoRow(
label = "曝光补偿范围",
value = "${camera.exposureCompensationRange.lower} - ${camera.exposureCompensationRange.upper} (步长: ${String.format("%.3f", camera.exposureCompensationStep)})"
)
camera.activeArraySize?.let { rect ->
InfoRow(
label = "传感器尺寸",
value = "${rect.width()} x ${rect.height()}"
)
}
}
}
@Composable
private fun InfoRow(
label: String,
value: String,
highlight: Boolean = false
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = label,
color = Color.Gray,
fontSize = 14.sp,
modifier = Modifier.weight(1f)
)
Text(
text = value,
color = if (highlight) Color(0xFFFFD700) else Color.White,
fontSize = 14.sp,
fontWeight = if (highlight) FontWeight.Bold else FontWeight.Normal,
fontFamily = FontFamily.Monospace,
modifier = Modifier.weight(1.5f)
)
}
}
/**
* 格式化曝光时间(纳秒 -> 可读格式)
*/
private fun formatExposureTime(nanos: Long): String {
val seconds = nanos / 1_000_000_000.0
return when {
seconds >= 1 -> "${String.format("%.1f", seconds)}s"
seconds >= 0.001 -> "1/${(1 / seconds).toInt()}"
else -> "${(nanos / 1_000_000.0).toInt()}ms"
}
}
@@ -0,0 +1,382 @@
package com.hinnka.mycamera.ui.components
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.widget.Toast
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.hinnka.mycamera.utils.PLog
/**
* 日志查看器弹窗
*/
@Composable
fun LogViewerDialog(
onDismiss: () -> Unit,
modifier: Modifier = Modifier
) {
val context = LocalContext.current
val logs = remember { PLog.getAllLogs() }
val logStats = remember { PLog.getLogStats() }
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(
usePlatformDefaultWidth = false,
dismissOnBackPress = true,
dismissOnClickOutside = true
)
) {
Surface(
modifier = modifier
.fillMaxWidth(0.95f)
.fillMaxHeight(0.9f),
shape = RoundedCornerShape(16.dp),
color = Color(0xFF2B2F3A)
) {
Column(
modifier = Modifier.fillMaxSize()
) {
// 标题栏
LogViewerHeader(
logCount = logs.size,
onCopyAll = {
val formattedLogs = PLog.getFormattedLogs()
copyToClipboard(context, formattedLogs)
},
onClear = {
PLog.clearLogs()
Toast.makeText(context, "日志已清空", Toast.LENGTH_SHORT).show()
onDismiss()
},
onDismiss = onDismiss
)
// 统计信息
LogStatsBar(logStats)
HorizontalDivider(
color = Color.White.copy(alpha = 0.1f),
modifier = Modifier.padding(horizontal = 16.dp)
)
// 日志内容区域
if (logs.isEmpty()) {
EmptyLogsView()
} else {
LogContentView(logs = logs, context = context)
}
}
}
}
}
/**
* 日志查看器头部
*/
@Composable
private fun LogViewerHeader(
logCount: Int,
onCopyAll: () -> Unit,
onClear: () -> Unit,
onDismiss: () -> Unit
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column {
Text(
text = "日志查看器",
color = Color.White,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
Text(
text = "共 $logCount 条日志",
color = Color.White.copy(alpha = 0.6f),
fontSize = 12.sp
)
}
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
// 复制全部按钮
IconButton(
onClick = onCopyAll,
colors = IconButtonDefaults.iconButtonColors(
containerColor = Color(0xFF4CAF50).copy(alpha = 0.2f)
)
) {
Icon(
imageVector = Icons.Default.ContentCopy,
contentDescription = "复制全部",
tint = Color(0xFF4CAF50)
)
}
// 清空按钮
IconButton(
onClick = onClear,
colors = IconButtonDefaults.iconButtonColors(
containerColor = Color(0xFFF44336).copy(alpha = 0.2f)
)
) {
Icon(
imageVector = Icons.Default.Clear,
contentDescription = "清空日志",
tint = Color(0xFFF44336)
)
}
// 关闭按钮
TextButton(onClick = onDismiss) {
Text(
text = "关闭",
color = Color.White,
fontSize = 14.sp
)
}
}
}
}
/**
* 日志统计栏
*/
@Composable
private fun LogStatsBar(logStats: Map<PLog.LogLevel, Int>) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
LogLevelChip("V", logStats[PLog.LogLevel.VERBOSE] ?: 0, Color(0xFF9E9E9E))
LogLevelChip("D", logStats[PLog.LogLevel.DEBUG] ?: 0, Color(0xFF2196F3))
LogLevelChip("I", logStats[PLog.LogLevel.INFO] ?: 0, Color(0xFF4CAF50))
LogLevelChip("W", logStats[PLog.LogLevel.WARNING] ?: 0, Color(0xFFFF9800))
LogLevelChip("E", logStats[PLog.LogLevel.ERROR] ?: 0, Color(0xFFF44336))
}
}
/**
* 日志等级标签
*/
@Composable
private fun RowScope.LogLevelChip(
level: String,
count: Int,
color: Color
) {
Surface(
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(8.dp),
color = color.copy(alpha = 0.2f)
) {
Row(
modifier = Modifier.padding(vertical = 6.dp, horizontal = 8.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = level,
color = color,
fontSize = 12.sp,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = count.toString(),
color = Color.White,
fontSize = 11.sp
)
}
}
}
/**
* 空日志视图
*/
@Composable
private fun EmptyLogsView() {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = "📋",
fontSize = 48.sp
)
Text(
text = "暂无日志记录",
color = Color.White.copy(alpha = 0.6f),
fontSize = 16.sp
)
Text(
text = "应用运行时的日志将显示在这里",
color = Color.White.copy(alpha = 0.4f),
fontSize = 12.sp
)
}
}
}
/**
* 日志内容视图
*/
@Composable
private fun LogContentView(
logs: List<PLog.LogEntry>,
context: Context
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Surface(
modifier = Modifier.fillMaxSize(),
shape = RoundedCornerShape(8.dp),
color = Color(0xFF1E1E1E)
) {
val verticalScrollState = rememberScrollState()
val horizontalScrollState = rememberScrollState()
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(verticalScrollState)
.horizontalScroll(horizontalScrollState)
.padding(12.dp)
) {
logs.forEach { logEntry ->
LogEntryItem(logEntry = logEntry, context = context)
}
}
}
}
}
/**
* 单条日志项
*/
@Composable
private fun LogEntryItem(
logEntry: PLog.LogEntry,
context: Context
) {
val levelColor = when (logEntry.level) {
PLog.LogLevel.VERBOSE -> Color(0xFF9E9E9E)
PLog.LogLevel.DEBUG -> Color(0xFF2196F3)
PLog.LogLevel.INFO -> Color(0xFF4CAF50)
PLog.LogLevel.WARNING -> Color(0xFFFF9800)
PLog.LogLevel.ERROR -> Color(0xFFF44336)
}
Column(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 8.dp)
) {
Row(
verticalAlignment = Alignment.Top,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
// 时间戳
Text(
text = logEntry.getFormattedTime(),
color = Color(0xFF888888),
fontSize = 10.sp,
fontFamily = FontFamily.Monospace
)
// 等级
Text(
text = when (logEntry.level) {
PLog.LogLevel.VERBOSE -> "V"
PLog.LogLevel.DEBUG -> "D"
PLog.LogLevel.INFO -> "I"
PLog.LogLevel.WARNING -> "W"
PLog.LogLevel.ERROR -> "E"
},
color = levelColor,
fontSize = 10.sp,
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.Monospace
)
// 标签
Text(
text = logEntry.tag,
color = Color(0xFF00BCD4),
fontSize = 10.sp,
fontWeight = FontWeight.Medium,
fontFamily = FontFamily.Monospace
)
}
// 消息
Text(
text = logEntry.message,
color = Color.White,
fontSize = 11.sp,
fontFamily = FontFamily.Monospace,
modifier = Modifier.padding(start = 4.dp, top = 2.dp)
)
// 异常堆栈
logEntry.throwable?.let { throwable ->
Text(
text = android.util.Log.getStackTraceString(throwable),
color = Color(0xFFFF5252),
fontSize = 10.sp,
fontFamily = FontFamily.Monospace,
modifier = Modifier.padding(start = 4.dp, top = 4.dp)
)
}
// 分隔线
HorizontalDivider(
color = Color.White.copy(alpha = 0.05f),
modifier = Modifier.padding(top = 8.dp)
)
}
}
/**
* 复制到剪贴板
*/
private fun copyToClipboard(context: Context, text: String) {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("日志", text)
clipboard.setPrimaryClip(clip)
Toast.makeText(context, "已复制到剪贴板", Toast.LENGTH_SHORT).show()
}
@@ -11,11 +11,15 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.FilterNone
import androidx.compose.material.icons.filled.Article
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -30,6 +34,7 @@ import com.hinnka.mycamera.R
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.frame.FrameInfo
import com.hinnka.mycamera.ui.camera.autoRotate
import com.hinnka.mycamera.ui.components.LogViewerDialog
import com.hinnka.mycamera.viewmodel.CameraViewModel
/**
@@ -48,9 +53,12 @@ fun SettingsScreen(
val volumeKeyCapture by viewModel.volumeKeyCapture.collectAsState(initial = false)
val autoSaveAfterCapture by viewModel.autoSaveAfterCapture.collectAsState(initial = true)
val isPurchased by viewModel.isPurchased.collectAsState()
val context = androidx.compose.ui.platform.LocalContext.current
// 日志查看器弹窗状态
var showLogViewerDialog by remember { mutableStateOf(false) }
val backgroundColor = Color(0xFF434A5D)
Column(
@@ -195,9 +203,55 @@ fun SettingsScreen(
)
}
Spacer(modifier = Modifier.height(24.dp))
// 开发者选项
SettingsSection(title = "开发者选项") {
// 日志收集按钮
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { showLogViewerDialog = true }
.padding(vertical = 8.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "日志收集",
color = Color.White,
fontSize = 16.sp,
fontWeight = FontWeight.Normal
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "查看和导出应用日志,用于问题诊断",
color = Color.White.copy(alpha = 0.6f),
fontSize = 13.sp,
lineHeight = 18.sp
)
}
Spacer(modifier = Modifier.width(16.dp))
Icon(
imageVector = Icons.Default.Article,
contentDescription = "日志",
tint = Color.White.copy(alpha = 0.6f)
)
}
}
Spacer(modifier = Modifier.height(32.dp))
}
}
// 显示日志查看器弹窗
if (showLogViewerDialog) {
LogViewerDialog(
onDismiss = { showLogViewerDialog = false }
)
}
}
/**
@@ -0,0 +1,181 @@
package com.hinnka.mycamera.utils
import android.os.Build
import android.util.Log
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.ConcurrentLinkedQueue
/**
* 日志管理工具
* 用于收集和管理应用日志
*/
object PLog {
private const val TAG = "LogManager"
private const val MAX_LOG_SIZE = 1000 // 最多保存1000条日志
// 使用线程安全的队列存储日志
private val logQueue = ConcurrentLinkedQueue<LogEntry>()
// 日志等级
enum class LogLevel {
VERBOSE, DEBUG, INFO, WARNING, ERROR
}
// 日志条目
data class LogEntry(
val timestamp: Long,
val level: LogLevel,
val tag: String,
val message: String,
val throwable: Throwable? = null
) {
fun getFormattedTime(): String {
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault())
return sdf.format(Date(timestamp))
}
fun getFormattedLog(): String {
val levelStr = when (level) {
LogLevel.VERBOSE -> "V"
LogLevel.DEBUG -> "D"
LogLevel.INFO -> "I"
LogLevel.WARNING -> "W"
LogLevel.ERROR -> "E"
}
val throwableStr = throwable?.let { "\n${Log.getStackTraceString(it)}" } ?: ""
return "${getFormattedTime()} $levelStr/$tag: $message$throwableStr"
}
}
/**
* 记录 VERBOSE 级别日志
*/
fun v(tag: String, message: String) {
addLog(LogLevel.VERBOSE, tag, message)
Log.v(tag, message)
}
/**
* 记录 DEBUG 级别日志
*/
fun d(tag: String, message: String) {
addLog(LogLevel.DEBUG, tag, message)
Log.d(tag, message)
}
/**
* 记录 INFO 级别日志
*/
fun i(tag: String, message: String) {
addLog(LogLevel.INFO, tag, message)
Log.i(tag, message)
}
/**
* 记录 WARNING 级别日志
*/
fun w(tag: String, message: String, throwable: Throwable? = null) {
addLog(LogLevel.WARNING, tag, message, throwable)
if (throwable != null) {
Log.w(tag, message, throwable)
} else {
Log.w(tag, message)
}
}
/**
* 记录 ERROR 级别日志
*/
fun e(tag: String, message: String, throwable: Throwable? = null) {
addLog(LogLevel.ERROR, tag, message, throwable)
if (throwable != null) {
Log.e(tag, message, throwable)
} else {
Log.e(tag, message)
}
}
/**
* 添加日志到队列
*/
private fun addLog(level: LogLevel, tag: String, message: String, throwable: Throwable? = null) {
val entry = LogEntry(
timestamp = System.currentTimeMillis(),
level = level,
tag = tag,
message = message,
throwable = throwable
)
logQueue.offer(entry)
// 如果超过最大数量,移除最早的日志
while (logQueue.size > MAX_LOG_SIZE) {
logQueue.poll()
}
}
/**
* 获取所有日志
*/
fun getAllLogs(): List<LogEntry> {
return logQueue.toList()
}
/**
* 获取格式化的所有日志文本
*/
fun getFormattedLogs(): String {
if (logQueue.isEmpty()) {
return "暂无日志记录"
}
return buildString {
appendLine("=== MyCamera 日志记录 ===")
appendLine("导出时间: ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())}")
appendLine("日志总数: ${logQueue.size}")
appendLine("厂商: ${Build.MANUFACTURER}")
appendLine("型号: ${Build.MODEL}")
appendLine("Android 版本: ${Build.VERSION.RELEASE}")
appendLine("=".repeat(50))
appendLine()
logQueue.forEach { entry ->
appendLine(entry.getFormattedLog())
}
}
}
/**
* 清空所有日志
*/
fun clearLogs() {
logQueue.clear()
Log.i(TAG, "日志已清空")
}
/**
* 获取指定等级的日志
*/
fun getLogsByLevel(level: LogLevel): List<LogEntry> {
return logQueue.filter { it.level == level }
}
/**
* 获取指定标签的日志
*/
fun getLogsByTag(tag: String): List<LogEntry> {
return logQueue.filter { it.tag == tag }
}
/**
* 获取日志统计信息
*/
fun getLogStats(): Map<LogLevel, Int> {
return LogLevel.entries.associateWith { level ->
logQueue.count { it.level == level }
}
}
}
@@ -45,9 +45,9 @@ class ShutterSoundPlayer(private val context: Context) {
soundPool?.setOnLoadCompleteListener { _, _, status ->
if (status == 0) {
isLoaded = true
Log.d(TAG, "Shutter sound loaded successfully")
PLog.d(TAG, "Shutter sound loaded successfully")
} else {
Log.e(TAG, "Failed to load shutter sound, status: $status")
PLog.e(TAG, "Failed to load shutter sound, status: $status")
}
}
@@ -55,9 +55,9 @@ class ShutterSoundPlayer(private val context: Context) {
soundId = soundPool?.load(afd, 1) ?: -1
afd.close()
Log.d(TAG, "Shutter sound player initialized with SoundPool")
PLog.d(TAG, "Shutter sound player initialized with SoundPool")
} catch (e: Exception) {
Log.e(TAG, "Failed to initialize shutter sound player", e)
PLog.e(TAG, "Failed to initialize shutter sound player", e)
isLoaded = false
}
}
@@ -67,7 +67,7 @@ class ShutterSoundPlayer(private val context: Context) {
*/
fun play() {
if (soundPool == null || soundId == -1 || !isLoaded) {
Log.w(TAG, "SoundPool not ready: soundPool=$soundPool, soundId=$soundId, isLoaded=$isLoaded")
PLog.w(TAG, "SoundPool not ready: soundPool=$soundPool, soundId=$soundId, isLoaded=$isLoaded")
// 如果是因为未初始化或加载失败,尝试重新初始化
if (soundPool == null) {
initializePlayer()
@@ -79,7 +79,7 @@ class ShutterSoundPlayer(private val context: Context) {
// 播放音效:左声道音量, 右声道音量, 优先级, 循环次数(0不循环), 播放速率(1.0正常)
soundPool?.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f)
} catch (e: Exception) {
Log.e(TAG, "Failed to play shutter sound", e)
PLog.e(TAG, "Failed to play shutter sound", e)
}
}
@@ -92,9 +92,9 @@ class ShutterSoundPlayer(private val context: Context) {
soundPool = null
soundId = -1
isLoaded = false
Log.d(TAG, "Shutter sound player released")
PLog.d(TAG, "Shutter sound player released")
} catch (e: Exception) {
Log.e(TAG, "Failed to release shutter sound player", e)
PLog.e(TAG, "Failed to release shutter sound player", e)
}
}
}
@@ -18,9 +18,9 @@ object YuvProcessor {
init {
try {
System.loadLibrary("my-native-lib")
Log.i(TAG, "Native library loaded successfully")
PLog.i(TAG, "Native library loaded successfully")
} catch (e: UnsatisfiedLinkError) {
Log.e(TAG, "Failed to load native library", e)
PLog.e(TAG, "Failed to load native library", e)
}
}
@@ -48,7 +48,7 @@ object YuvProcessor {
// 获取目标宽高比(长边/短边)
val targetRatio = aspectRatio.getValue(true)
// Log.d(TAG, "Processing image: ${width}x${height}, rotation=$rotation, ratio=$targetRatio")
// PLog.d(TAG, "Processing image: ${width}x${height}, rotation=$rotation, ratio=$targetRatio")
// 调用 native 方法处理
val result = processYuv(
@@ -59,7 +59,7 @@ object YuvProcessor {
)
if (result == null || result.size < 3) {
Log.e(TAG, "Native processing failed, using fallback")
PLog.e(TAG, "Native processing failed, using fallback")
return fallbackProcess(image, aspectRatio)
}
@@ -68,7 +68,7 @@ object YuvProcessor {
val outputHeight = result[1]
val pixels = result.copyOfRange(2, result.size)
// Log.d(TAG, "Creating bitmap: ${outputWidth}x${outputHeight}")
// PLog.d(TAG, "Creating bitmap: ${outputWidth}x${outputHeight}")
// 创建 Bitmap
return Bitmap.createBitmap(pixels, outputWidth, outputHeight, Bitmap.Config.ARGB_8888)
@@ -78,7 +78,7 @@ object YuvProcessor {
* 后备处理方法(如果 native 处理失败)
*/
private fun fallbackProcess(image: Image, aspectRatio: AspectRatio): Bitmap {
Log.w(TAG, "Using fallback YUV processing")
PLog.w(TAG, "Using fallback YUV processing")
val planes = image.planes
val width = image.width
@@ -27,6 +27,7 @@ import com.hinnka.mycamera.lut.LutConfig
import com.hinnka.mycamera.lut.LutImageProcessor
import com.hinnka.mycamera.lut.LutInfo
import com.hinnka.mycamera.utils.OrientationObserver
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.utils.ShutterSoundPlayer
import com.hinnka.mycamera.utils.YuvProcessor
import kotlinx.coroutines.*
@@ -151,14 +152,14 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
viewModelScope.launch {
contentRepository.availableLuts.collect { luts ->
availableLutList = luts
Log.d(TAG, "CameraViewModel: availableLutList updated to ${luts.size} items")
PLog.d(TAG, "CameraViewModel: availableLutList updated to ${luts.size} items")
}
}
viewModelScope.launch {
contentRepository.availableFrames.collect { frames ->
availableFrameList = frames
Log.d(TAG, "CameraViewModel: availableFrameList updated to ${frames.size} items")
PLog.d(TAG, "CameraViewModel: availableFrameList updated to ${frames.size} items")
}
}
@@ -414,7 +415,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
// StateFlow 会自动更新 availableLutList 和 availableFrameList
contentRepository.refreshCustomContent()
}
Log.d(TAG, "Custom content refreshed via ContentRepository")
PLog.d(TAG, "Custom content refreshed via ContentRepository")
}
}
@@ -471,7 +472,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
*/
fun captureAndGenerateLutPreviews() {
if (isGeneratingPreviews) {
Log.d(TAG, "Already generating previews, skipping")
PLog.d(TAG, "Already generating previews, skipping")
return
}
@@ -508,10 +509,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
lutPreviewBitmaps.values.forEach { it.recycle() }
lutPreviewBitmaps = newPreviews
isGeneratingPreviews = false
Log.d(TAG, "Generated ${newPreviews.size} LUT previews from YUV")
PLog.d(TAG, "Generated ${newPreviews.size} LUT previews from YUV")
}
} catch (e: Exception) {
Log.e(TAG, "Failed to generate LUT previews", e)
PLog.e(TAG, "Failed to generate LUT previews", e)
isGeneratingPreviews = false
}
}
@@ -565,7 +566,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val imageBytes = out.toByteArray()
android.graphics.BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
} catch (e: Exception) {
Log.e(TAG, "Failed to convert YUV to Bitmap", e)
PLog.e(TAG, "Failed to convert YUV to Bitmap", e)
null
}
}
@@ -745,10 +746,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val photoId = PhotoManager.savePhoto(context, bitmap, metadata, captureInfo)
if (photoId != null) {
Log.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave")
PLog.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave")
_imageSavedEvent.emit(Unit)
} else {
Log.e(TAG, "Failed to save image via PhotoManager")
PLog.e(TAG, "Failed to save image via PhotoManager")
}
}
@@ -787,7 +788,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
}
} catch (e: Exception) {
Log.e(TAG, "Failed to save image", e)
PLog.e(TAG, "Failed to save image", e)
// 确保即使出错也关闭 Image
try {
image.close()
@@ -19,6 +19,7 @@ import com.hinnka.mycamera.frame.FrameInfo
import com.hinnka.mycamera.frame.FrameRenderer
import com.hinnka.mycamera.gallery.*
import com.hinnka.mycamera.lut.*
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -135,14 +136,14 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
viewModelScope.launch {
contentRepository.availableLuts.collect { luts ->
availableLuts = luts
Log.d(TAG, "GalleryViewModel: availableLuts updated to ${luts.size} items")
PLog.d(TAG, "GalleryViewModel: availableLuts updated to ${luts.size} items")
}
}
viewModelScope.launch {
contentRepository.availableFrames.collect { frames ->
availableFrames = frames
Log.d(TAG, "GalleryViewModel: availableFrames updated to ${frames.size} items")
PLog.d(TAG, "GalleryViewModel: availableFrames updated to ${frames.size} items")
}
}
}
@@ -206,7 +207,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
_photos.value = finalPhotos
}
} catch (e: Exception) {
Log.e(TAG, "Failed to load photos", e)
PLog.e(TAG, "Failed to load photos", e)
_isLoading.value = false
}
}
@@ -236,7 +237,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
updatedPhoto = updatedPhoto.copy(metadata = newMetadata)
}
} catch (e: Exception) {
Log.e(TAG, "Failed to load dimensions for ${photo.id}", e)
PLog.e(TAG, "Failed to load dimensions for ${photo.id}", e)
}
} else if (metadata != null) {
// Already has width/height from metadata
@@ -280,7 +281,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
PhotoManager.saveMetadata(context, it.id, newMetadata)
}
} catch (e: Exception) {
Log.e(TAG, "Failed to load dimensions for latest photo", e)
PLog.e(TAG, "Failed to load dimensions for latest photo", e)
}
}
_latestPhoto.value = updatedPhoto
@@ -651,7 +652,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
photoProcessor.process(context, bitmap, metadata, photo.previewUri)
} catch (e: Exception) {
Log.e(TAG, "Failed to create preview", e)
PLog.e(TAG, "Failed to create preview", e)
null
}
}
@@ -704,7 +705,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
onComplete(success)
} catch (e: Exception) {
Log.e(TAG, "Failed to save metadata", e)
PLog.e(TAG, "Failed to save metadata", e)
onComplete(false)
}
}
@@ -787,7 +788,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
sharedFile
} catch (e: Exception) {
Log.e(TAG, "Failed to prepare shared photo", e)
PLog.e(TAG, "Failed to prepare shared photo", e)
null
}
}
@@ -842,7 +843,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
onComplete(uri != null)
} catch (e: Exception) {
Log.e(TAG, "Failed to export photo", e)
PLog.e(TAG, "Failed to export photo", e)
onComplete(false)
}
}
@@ -898,7 +899,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// StateFlow 会自动更新 availableLuts 和 availableFrames
contentRepository.refreshCustomContent()
}
Log.d(TAG, "Custom content refreshed via ContentRepository")
PLog.d(TAG, "Custom content refreshed via ContentRepository")
}
}
}