feat: quick shot mode

This commit is contained in:
zhoubinjia committed 2026-06-18 15:59:17 +08:00
1 parent b4931989b3
commit e7a4a0431d
15 files changed
+954 -41

No files matched your search

@@ -32,6 +32,8 @@ import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.utils.DeviceUtil
import com.hinnka.mycamera.utils.OrientationObserver
import com.hinnka.mycamera.video.CaptureMode
import com.hinnka.mycamera.video.QuickShotCapabilitiesResolver
import com.hinnka.mycamera.video.QuickShotResolutionPreset
import com.hinnka.mycamera.video.VideoAspectRatio
import com.hinnka.mycamera.video.VIDEO_AUDIO_INPUT_AUTO
import com.hinnka.mycamera.video.VideoBitratePreset
@@ -788,6 +790,37 @@ class Camera2Controller(private val context: Context) {
return snapshot.previewSize
}
private fun refreshQuickShotCapabilities(characteristics: CameraCharacteristics? = null): Size {
val openCameraId = getCurrentOpenCameraId()
if (openCameraId.isEmpty()) {
return _state.value.currentPreviewSize
}
val resolvedCharacteristics = try {
characteristics ?: cachedCharacteristics ?: cameraManager.getCameraCharacteristics(openCameraId)
} catch (e: Exception) {
PLog.e(TAG, "Failed to load quick-shot capabilities", e)
return _state.value.currentPreviewSize
}
val snapshot = QuickShotCapabilitiesResolver.resolve(
characteristics = resolvedCharacteristics,
requestedConfig = _state.value.quickShotConfig,
aspectRatio = _state.value.aspectRatio
)
_state.value = _state.value.copy(
quickShotConfig = snapshot.config,
quickShotCapabilities = snapshot.capabilities,
currentPreviewSize = if (_state.value.captureMode == CaptureMode.QUICK_SHOT) {
snapshot.previewSize
} else {
_state.value.currentPreviewSize
}
)
return snapshot.previewSize
}
private fun startVideoRecordingTicker() {
stopVideoRecordingTicker()
videoRecordingStartElapsedMs = SystemClock.elapsedRealtime()
@@ -932,8 +965,10 @@ class Camera2Controller(private val context: Context) {
}
val resolvedVideoPreviewSize = refreshVideoCapabilities(cachedCharacteristics)
val resolvedQuickShotPreviewSize = refreshQuickShotCapabilities(cachedCharacteristics)
previewSize = when (captureMode) {
CaptureMode.VIDEO -> resolvedVideoPreviewSize
CaptureMode.QUICK_SHOT -> resolvedQuickShotPreviewSize
CaptureMode.PHOTO -> CameraUtils.getFixedPreviewSize(context, openCameraId, _state.value.aspectRatio)
}
surfaceTexture.setDefaultBufferSize(previewSize.width, previewSize.height)
@@ -961,7 +996,11 @@ class Camera2Controller(private val context: Context) {
isHlg10Supported = isHlg10Supported,
availableNrModes = selectableNrModes,
currentPreviewSize = previewSize,
currentCaptureSize = if (captureMode == CaptureMode.VIDEO) previewSize else _state.value.currentCaptureSize,
currentCaptureSize = if (captureMode == CaptureMode.VIDEO || captureMode == CaptureMode.QUICK_SHOT) {
previewSize
} else {
_state.value.currentCaptureSize
},
minimumFocusDistance = minimumFocusDistance
)
refreshHyperfocalFocusDistanceIfEnabled(updatePreview = false)
@@ -1710,7 +1749,7 @@ class Camera2Controller(private val context: Context) {
return CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE
}
val preferredModes = if (captureMode == CaptureMode.VIDEO) {
val preferredModes = if (captureMode == CaptureMode.VIDEO || captureMode == CaptureMode.QUICK_SHOT) {
intArrayOf(
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO,
CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE,
@@ -3512,6 +3551,9 @@ class Camera2Controller(private val context: Context) {
*/
fun setAspectRatio(ratio: AspectRatio) {
_state.value = _state.value.copy(aspectRatio = ratio)
if (_state.value.captureMode == CaptureMode.QUICK_SHOT) {
refreshQuickShotCapabilities()
}
}
/**
@@ -3546,6 +3588,11 @@ class Camera2Controller(private val context: Context) {
if (mode == CaptureMode.VIDEO) {
livePhotoRecorder.stopRecording()
refreshVideoCapabilities()
} else if (mode == CaptureMode.QUICK_SHOT) {
livePhotoRecorder.stopRecording()
stopVideoRecordingTicker()
_state.value = _state.value.copy(videoRecordingState = VideoRecordingState())
refreshQuickShotCapabilities()
} else {
stopVideoRecordingTicker()
_state.value = _state.value.copy(videoRecordingState = VideoRecordingState())
@@ -3560,6 +3607,20 @@ class Camera2Controller(private val context: Context) {
refreshVideoCapabilities()
}
fun setQuickShotResolution(resolution: QuickShotResolutionPreset) {
_state.value = _state.value.copy(
quickShotConfig = _state.value.quickShotConfig.copy(resolution = resolution)
)
refreshQuickShotCapabilities()
}
fun setQuickShotCaptureState(isCapturing: Boolean, burstCapturing: Boolean = false) {
_state.value = _state.value.copy(
isCapturing = isCapturing,
burstCapturing = burstCapturing
)
}
fun setVideoFps(fps: VideoFpsPreset) {
_state.value = _state.value.copy(videoConfig = _state.value.videoConfig.copy(fps = fps))
refreshVideoCapabilities()
@@ -4,6 +4,8 @@ import android.graphics.Rect
import android.util.Range
import android.util.Size
import com.hinnka.mycamera.video.CaptureMode
import com.hinnka.mycamera.video.QuickShotCapabilities
import com.hinnka.mycamera.video.QuickShotConfig
import com.hinnka.mycamera.video.VideoCapabilities
import com.hinnka.mycamera.video.VideoConfig
import com.hinnka.mycamera.video.VideoRecordingState
@@ -351,6 +353,8 @@ data class CameraState(
val isP3Supported: Boolean = false,
val currentDynamicRangeProfile: String = "STANDARD",
val captureMode: CaptureMode = CaptureMode.PHOTO,
val quickShotConfig: QuickShotConfig = QuickShotConfig(),
val quickShotCapabilities: QuickShotCapabilities = QuickShotCapabilities(),
val videoConfig: VideoConfig = VideoConfig(),
val videoCapabilities: VideoCapabilities = VideoCapabilities(),
val videoRecordingState: VideoRecordingState = VideoRecordingState(),
@@ -432,7 +436,7 @@ data class CameraState(
fun getPreviewAspectRatio(): Float {
return when (captureMode) {
CaptureMode.PHOTO -> aspectRatio.getValue(isLandscape = false)
CaptureMode.PHOTO, CaptureMode.QUICK_SHOT -> aspectRatio.getValue(isLandscape = false)
CaptureMode.VIDEO -> videoConfig.aspectRatio.getPortraitAspectRatio(
videoCapabilities.openGatePortraitAspectRatio
)
@@ -31,6 +31,7 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import com.hinnka.mycamera.utils.DeviceUtil
import com.hinnka.mycamera.video.CaptureMode
import com.hinnka.mycamera.video.QuickShotResolutionPreset
import com.hinnka.mycamera.video.VideoAspectRatio
import com.hinnka.mycamera.video.VIDEO_AUDIO_INPUT_AUTO
import com.hinnka.mycamera.video.VideoBitratePreset
@@ -161,6 +162,7 @@ data class UserPreferences(
val useHlg10: Boolean = false,
val hlgHardwareCompatibilityEnabled: Boolean = false,
val useP3ColorSpace: Boolean = false,
val quickShotResolution: QuickShotResolutionPreset = QuickShotResolutionPreset.FHD_1080P,
val videoResolution: VideoResolutionPreset = VideoResolutionPreset.FHD_1080P,
val videoFps: VideoFpsPreset = VideoFpsPreset.FPS_30,
val videoAspectRatio: VideoAspectRatio = VideoAspectRatio.RATIO_16_9,
@@ -332,6 +334,7 @@ class UserPreferencesRepository(private val context: Context) {
private val USE_HLG10 = booleanPreferencesKey("use_hlg10")
private val HLG_HARDWARE_COMPATIBILITY_ENABLED = booleanPreferencesKey("hlg_hardware_compatibility_enabled")
private val USE_P3_COLOR_SPACE = booleanPreferencesKey("use_p3_color_space")
private val QUICK_SHOT_RESOLUTION = stringPreferencesKey("quick_shot_resolution")
private val VIDEO_RESOLUTION = stringPreferencesKey("video_resolution")
private val VIDEO_FPS = stringPreferencesKey("video_fps")
private val VIDEO_ASPECT_RATIO = stringPreferencesKey("video_aspect_ratio")
@@ -487,6 +490,11 @@ class UserPreferencesRepository(private val context: Context) {
useHlg10 = preferences[USE_HLG10] ?: false,
hlgHardwareCompatibilityEnabled = preferences[HLG_HARDWARE_COMPATIBILITY_ENABLED] ?: false,
useP3ColorSpace = preferences[USE_P3_COLOR_SPACE] ?: false,
quickShotResolution = runCatching {
QuickShotResolutionPreset.valueOf(
preferences[QUICK_SHOT_RESOLUTION] ?: QuickShotResolutionPreset.FHD_1080P.name
)
}.getOrDefault(QuickShotResolutionPreset.FHD_1080P),
videoResolution = VideoResolutionPreset.valueOf(
preferences[VIDEO_RESOLUTION] ?: VideoResolutionPreset.FHD_1080P.name
),
@@ -1476,6 +1484,12 @@ class UserPreferencesRepository(private val context: Context) {
}
}
suspend fun saveQuickShotResolution(resolution: QuickShotResolutionPreset) {
context.dataStore.edit { preferences ->
preferences[QUICK_SHOT_RESOLUTION] = resolution.name
}
}
suspend fun saveVideoResolution(resolution: VideoResolutionPreset) {
context.dataStore.edit { preferences ->
preferences[VIDEO_RESOLUTION] = resolution.name
@@ -3046,6 +3046,54 @@ object GalleryManager {
}
}
suspend fun saveBitmapBurstPhoto(
context: Context,
photoId: String,
bitmap: Bitmap,
shouldAutoSave: Boolean = true,
photoProcessor: PhotoProcessor,
sharpeningValue: Float,
noiseReductionValue: Float,
chromaNoiseReductionValue: Float,
photoQuality: Int = 95
) = withContext(Dispatchers.IO) {
val photoDir = getPhotoDir(context, photoId, true)
val mainPhotoFile = File(photoDir, PHOTO_FILE)
val burstDir = File(photoDir, BURST_DIR)
if (!burstDir.exists()) {
burstDir.mkdirs()
}
try {
val photoFile = File(burstDir, System.currentTimeMillis().toString() + ".jpg")
val metadata = loadMetadata(context, photoId) ?: return@withContext
FileOutputStream(photoFile).use { outputStream ->
writeFinalJpeg(bitmap, outputStream, photoQuality)
}
if (!mainPhotoFile.exists() || mainPhotoFile.length() == 0L) {
FileOutputStream(mainPhotoFile).use { outputStream ->
writeFinalJpeg(bitmap, outputStream, photoQuality)
}
if (shouldAutoSave) {
exportPhoto(
context,
photoId,
bitmap,
photoProcessor,
metadata,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality
)
}
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to save bitmap burst photo", e)
}
}
/**
* 获取指定照片的连拍照片文件列表
*/
@@ -93,6 +93,7 @@ class LutRenderer : GLSurfaceView.Renderer {
private const val TEXTURE_COORD_COMPONENT_COUNT = 2
private const val BYTES_PER_FLOAT = 4
private const val BYTES_PER_SHORT = 2
private const val DEFAULT_PREVIEW_CAPTURE_MAX_LONG_EDGE = 1080
}
// 着色器程序 ID
@@ -522,7 +523,7 @@ class LutRenderer : GLSurfaceView.Renderer {
private var captureWidth = 512
private var captureHeight = 512
private var captureAspectRatio = 0f
private val maxCaptureSize = 1080 // 预览图最大尺寸
private var captureMaxLongEdge = DEFAULT_PREVIEW_CAPTURE_MAX_LONG_EDGE
private var lastCaptureWidth = 0
private var lastCaptureHeight = 0
@@ -2618,11 +2619,11 @@ class LutRenderer : GLSurfaceView.Renderer {
}
if (targetAspectRatio >= 1f) {
captureWidth = maxCaptureSize
captureHeight = (maxCaptureSize / targetAspectRatio).toInt()
captureWidth = captureMaxLongEdge
captureHeight = (captureMaxLongEdge / targetAspectRatio).toInt()
} else {
captureHeight = maxCaptureSize
captureWidth = (maxCaptureSize * targetAspectRatio).toInt()
captureHeight = captureMaxLongEdge
captureWidth = (captureMaxLongEdge * targetAspectRatio).toInt()
}
captureWidth = captureWidth.coerceAtLeast(1)
captureHeight = captureHeight.coerceAtLeast(1)
@@ -2633,7 +2634,9 @@ class LutRenderer : GLSurfaceView.Renderer {
* 请求捕获预览帧
* 会在下一帧渲染后捕获并通过回调返回
*/
fun capturePreviewFrame() {
fun capturePreviewFrame(maxLongEdge: Int = DEFAULT_PREVIEW_CAPTURE_MAX_LONG_EDGE) {
captureMaxLongEdge = maxLongEdge.coerceAtLeast(1)
updateCaptureSize()
shouldCapturePreview = true
}
@@ -276,6 +276,22 @@ class CameraGLSurfaceView @JvmOverloads constructor(
* @param callback 捕获完成后的回调,在主线程调用
*/
fun capturePreviewFrame(callback: (Bitmap) -> Unit) {
capturePreviewFrameInternal(maxLongEdge = null, requestRenderImmediately = true, callback = callback)
}
fun capturePreviewFrame(maxLongEdge: Int, callback: (Bitmap) -> Unit) {
capturePreviewFrameInternal(maxLongEdge = maxLongEdge, requestRenderImmediately = true, callback = callback)
}
fun captureNextPreviewFrame(maxLongEdge: Int, callback: (Bitmap) -> Unit) {
capturePreviewFrameInternal(maxLongEdge = maxLongEdge, requestRenderImmediately = false, callback = callback)
}
private fun capturePreviewFrameInternal(
maxLongEdge: Int?,
requestRenderImmediately: Boolean,
callback: (Bitmap) -> Unit
) {
renderer.onPreviewFrameCaptured = { bitmap ->
// 在主线程回调
post {
@@ -283,8 +299,14 @@ class CameraGLSurfaceView @JvmOverloads constructor(
}
}
queueEvent {
renderer.capturePreviewFrame()
requestRender()
if (maxLongEdge != null) {
renderer.capturePreviewFrame(maxLongEdge)
} else {
renderer.capturePreviewFrame()
}
if (requestRenderImmediately) {
requestRender()
}
}
}
@@ -22,6 +22,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Undo
import androidx.compose.material.icons.filled.CameraAlt
import androidx.compose.material.icons.filled.Cameraswitch
import androidx.compose.material.icons.filled.Bolt
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Layers
import androidx.compose.material.icons.filled.Pause
@@ -79,6 +80,7 @@ import com.hinnka.mycamera.utils.OrientationObserver
import com.hinnka.mycamera.viewmodel.CameraViewModel
import com.hinnka.mycamera.viewmodel.GalleryViewModel
import com.hinnka.mycamera.video.CaptureMode
import com.hinnka.mycamera.video.QuickShotResolutionPreset
import com.hinnka.mycamera.video.VideoAspectRatio
import com.hinnka.mycamera.video.VideoFpsPreset
import com.hinnka.mycamera.video.VideoLogProfile
@@ -208,6 +210,7 @@ fun CameraScreen(
val rawSpectralFilmPrint by viewModel.rawSpectralFilmPrint.collectAsState()
val multipleExposureState = viewModel.multipleExposureState
val canStartShutterAnimation by viewModel.canStartShutterAnimation.collectAsState()
val currentCaptureModeForEffects by rememberUpdatedState(state.captureMode)
var previewRecipeParamsOverride by remember(currentLutId) { mutableStateOf<ColorRecipeParams?>(null) }
var pendingCaptureAnimationBitmap by remember { mutableStateOf<Bitmap?>(null) }
var previewBounds by remember { mutableStateOf<Rect?>(null) }
@@ -318,7 +321,7 @@ fun CameraScreen(
LaunchedEffect(Unit) {
viewModel.imageSavedEvent.collect {
galleryViewModel.refreshLatestPhoto()
if (!enableDevelopAnimation) {
if (!enableDevelopAnimation || currentCaptureModeForEffects != CaptureMode.PHOTO) {
pendingCaptureAnimationBitmap = null
captureAnimationSnapshot = null
MyCameraApplication.updateWidgets(context)
@@ -506,7 +509,9 @@ fun CameraScreen(
canStartShutterAnimation
) {
val canRevealInitialPreview =
canStartShutterAnimation || state.captureMode == CaptureMode.VIDEO
canStartShutterAnimation ||
state.captureMode == CaptureMode.VIDEO ||
state.captureMode == CaptureMode.QUICK_SHOT
if (hasPlayedInitialPreviewTransition || !state.isPreviewActive || !canRevealInitialPreview) return@LaunchedEffect
previewTransitionActive = true
delay(InitialPreviewTransitionDelayMillis)
@@ -519,7 +524,7 @@ fun CameraScreen(
var showGhostPermissionDialog by remember { mutableStateOf(false) }
LaunchedEffect(state.captureMode) {
if (state.captureMode == CaptureMode.VIDEO) {
if (state.captureMode != CaptureMode.PHOTO) {
showVideoParameterRuler = false
}
}
@@ -616,6 +621,7 @@ fun CameraScreen(
val backgroundPainter = rememberBackgroundPainter(viewModel)
val isVideoMode = state.captureMode == CaptureMode.VIDEO
val isPhotoStyleMode = state.captureMode != CaptureMode.VIDEO
val videoAspectRatio =
state.videoConfig.aspectRatio.getPortraitAspectRatio(state.videoCapabilities.openGatePortraitAspectRatio)
@@ -660,6 +666,11 @@ fun CameraScreen(
},
useLivePhoto = useLivePhoto,
onLivePhotoToggle = { viewModel.setUseLivePhoto(!state.useLivePhoto) },
quickShotConfig = state.quickShotConfig,
quickShotCapabilities = state.quickShotCapabilities,
onQuickShotResolutionClick = {
cycleQuickShotResolution(state)?.let(viewModel::setQuickShotResolution)
},
videoConfig = state.videoConfig,
videoCapabilities = state.videoCapabilities,
onVideoTorchToggle = { viewModel.setVideoTorchEnabled(!state.videoConfig.torchEnabled) },
@@ -1001,7 +1012,7 @@ fun CameraScreen(
}
// 实时直方图 (Overlaid on preview if enabled)
if (state.captureMode == CaptureMode.PHOTO && state.histogram != null && viewModel.showHistogram) {
if (isPhotoStyleMode && state.histogram != null && viewModel.showHistogram) {
HistogramView(
histogram = state.histogram,
modifier = Modifier
@@ -1036,14 +1047,14 @@ fun CameraScreen(
)
}
if (burstCapturingCount > 0) {
if (state.burstCapturing && burstCapturingCount > 0) {
BurstCaptureOverlay(
count = burstCapturingCount,
modifier = Modifier.fillMaxSize()
)
}
if (useMultipleExposure) {
if (useMultipleExposure && state.captureMode == CaptureMode.PHOTO) {
MultipleExposureOverlay(
state = multipleExposureState,
onFinish = { viewModel.finishMultipleExposureSession() },
@@ -1053,8 +1064,8 @@ fun CameraScreen(
)
}
// Zoom bar overlaid on preview (only in Photo mode)
if (state.captureMode == CaptureMode.PHOTO) {
// Zoom bar overlaid on preview for photo-style modes.
if (isPhotoStyleMode) {
Box(
modifier = Modifier
.fillMaxSize()
@@ -1072,7 +1083,7 @@ fun CameraScreen(
color = Color.Black
)
}
if (state.captureMode == CaptureMode.PHOTO) {
if (isPhotoStyleMode) {
parameterRuler()
}
}
@@ -1237,7 +1248,7 @@ fun CameraScreen(
AnimatedVisibility(
visible = !isXpan && state.captureMode == CaptureMode.PHOTO,
visible = !isXpan && isPhotoStyleMode,
) {
parameterBar { param ->
selectedParameter = param
@@ -1306,6 +1317,9 @@ fun CameraScreen(
videoAudioInputId = state.videoConfig.audioInputId,
videoAudioInputOptions = videoAudioInputOptions,
onVideoAudioInputChange = { viewModel.setVideoAudioInputId(it) },
quickShotResolution = state.quickShotConfig.resolution,
quickShotCapabilities = state.quickShotCapabilities,
onQuickShotResolutionChange = { runPreviewTransition { viewModel.setQuickShotResolution(it) } },
useRaw = useRaw && state.isRawSupported,
onRawToggle = { viewModel.setUseRaw(it) },
isRawSupported = state.isRawSupported,
@@ -1697,7 +1711,8 @@ fun Controls(
isCapturing = state.isCapturing,
isVideoRecording = state.videoRecordingState.isRecording,
isPaused = state.videoRecordingState.isPaused,
allowLongPress = state.captureMode == CaptureMode.PHOTO && !useMultipleExposure,
allowLongPress = (state.captureMode == CaptureMode.PHOTO && !useMultipleExposure) ||
state.captureMode == CaptureMode.QUICK_SHOT,
multipleExposureEnabled = useMultipleExposure && state.captureMode == CaptureMode.PHOTO,
multipleExposureProgress = multipleExposureState.capturedCount.toFloat() /
multipleExposureState.targetCount.coerceAtLeast(1).toFloat(),
@@ -1937,7 +1952,7 @@ private fun CaptureModeSwitcher(
Box(
modifier = Modifier
.width(100.dp)
.width(148.dp)
.height(30.dp)
.clip(RoundedCornerShape(16.dp))
.background(Color.White.copy(alpha = 0.12f))
@@ -1945,7 +1960,11 @@ private fun CaptureModeSwitcher(
) {
val knobWidth = 48.dp
val knobOffset by animateDpAsState(
targetValue = if (captureMode == CaptureMode.PHOTO) 0.dp else 48.dp,
targetValue = when (captureMode) {
CaptureMode.PHOTO -> 0.dp
CaptureMode.QUICK_SHOT -> 48.dp
CaptureMode.VIDEO -> 96.dp
},
animationSpec = tween(durationMillis = 220),
label = "modeSwitcher"
)
@@ -1965,13 +1984,23 @@ private fun CaptureModeSwitcher(
icon = Icons.Default.CameraAlt,
selected = captureMode == CaptureMode.PHOTO,
enabled = enabled,
contentDescription = stringResource(R.string.capture_mode_photo),
onClick = { onModeSelected(CaptureMode.PHOTO) },
modifier = Modifier.weight(1f)
)
ModeSwitcherItem(
icon = Icons.Default.Bolt,
selected = captureMode == CaptureMode.QUICK_SHOT,
enabled = enabled,
contentDescription = stringResource(R.string.capture_mode_quick_shot),
onClick = { onModeSelected(CaptureMode.QUICK_SHOT) },
modifier = Modifier.weight(1f)
)
ModeSwitcherItem(
icon = Icons.Default.Videocam,
selected = captureMode == CaptureMode.VIDEO,
enabled = enabled,
contentDescription = stringResource(R.string.capture_mode_video),
onClick = { onModeSelected(CaptureMode.VIDEO) },
modifier = Modifier.weight(1f)
)
@@ -1984,6 +2013,7 @@ private fun ModeSwitcherItem(
icon: ImageVector,
selected: Boolean,
enabled: Boolean,
contentDescription: String,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
@@ -1996,7 +2026,7 @@ private fun ModeSwitcherItem(
) {
Icon(
imageVector = icon,
contentDescription = null,
contentDescription = contentDescription,
tint = if (selected) Color.Black else Color.White,
modifier = Modifier.size(18.dp)
)
@@ -2007,6 +2037,10 @@ private fun cycleVideoResolution(state: CameraState): VideoResolutionPreset? {
return nextOption(state.videoConfig.resolution, state.videoCapabilities.availableResolutions)
}
private fun cycleQuickShotResolution(state: CameraState): QuickShotResolutionPreset? {
return nextOption(state.quickShotConfig.resolution, state.quickShotCapabilities.availableResolutions)
}
private fun cycleVideoFps(state: CameraState): VideoFpsPreset? {
return nextOption(state.videoConfig.fps, state.videoCapabilities.availableFps)
}
@@ -31,6 +31,9 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.hinnka.mycamera.R
import com.hinnka.mycamera.video.CaptureMode
import com.hinnka.mycamera.video.QuickShotCapabilities
import com.hinnka.mycamera.video.QuickShotConfig
import com.hinnka.mycamera.video.QuickShotResolutionPreset
import com.hinnka.mycamera.video.VideoAspectRatio
import com.hinnka.mycamera.video.VideoCapabilities
import com.hinnka.mycamera.video.VideoConfig
@@ -50,6 +53,9 @@ fun CameraTopBar(
onHistogramToggle: () -> Unit,
useLivePhoto: Boolean,
onLivePhotoToggle: () -> Unit,
quickShotConfig: QuickShotConfig,
quickShotCapabilities: QuickShotCapabilities,
onQuickShotResolutionClick: () -> Unit,
videoConfig: VideoConfig,
videoCapabilities: VideoCapabilities,
onVideoTorchToggle: () -> Unit,
@@ -75,6 +81,23 @@ fun CameraTopBar(
return
}
if (captureMode == CaptureMode.QUICK_SHOT) {
QuickShotTopBar(
flashMode = flashMode,
onFlashToggle = onFlashToggle,
timerSeconds = timerSeconds,
onTimerToggle = onTimerToggle,
showHistogram = showHistogram,
onHistogramToggle = onHistogramToggle,
quickShotConfig = quickShotConfig,
quickShotCapabilities = quickShotCapabilities,
onQuickShotResolutionClick = onQuickShotResolutionClick,
onSettingsClick = onSettingsClick,
modifier = modifier
)
return
}
Row(
modifier = modifier
.fillMaxWidth()
@@ -144,6 +167,94 @@ fun CameraTopBar(
}
}
@Composable
private fun QuickShotTopBar(
flashMode: Int,
onFlashToggle: () -> Unit,
timerSeconds: Int,
onTimerToggle: () -> Unit,
showHistogram: Boolean,
onHistogramToggle: () -> Unit,
quickShotConfig: QuickShotConfig,
quickShotCapabilities: QuickShotCapabilities,
onQuickShotResolutionClick: () -> Unit,
onSettingsClick: () -> Unit,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier
.fillMaxWidth()
.padding(top = 32.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
IconButton(onClick = onFlashToggle) {
Icon(
imageVector = when (flashMode) {
0 -> Icons.Default.FlashOff
1 -> Icons.Default.FlashOn
2 -> Icons.Default.FlashlightOn
else -> Icons.Default.FlashOff
},
modifier = Modifier.size(20.dp).autoRotate(),
contentDescription = stringResource(R.string.flash),
tint = Color.White
)
}
IconButton(onClick = onTimerToggle) {
if (timerSeconds > 0) {
Text(
text = "${timerSeconds}s",
color = Color.Yellow,
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.autoRotate()
)
} else {
Icon(
imageVector = Icons.Default.Timer,
contentDescription = stringResource(R.string.timer),
modifier = Modifier.size(20.dp).autoRotate(),
tint = Color.White
)
}
}
IconButton(
onClick = onQuickShotResolutionClick,
enabled = quickShotCapabilities.availableResolutions.size > 1
) {
Text(
text = quickShotResolutionLabel(quickShotConfig.resolution),
color = if (quickShotCapabilities.availableResolutions.size > 1) Color.White else Color.White.copy(alpha = 0.5f),
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.Monospace,
modifier = Modifier.autoRotate()
)
}
IconButton(onClick = onHistogramToggle) {
Icon(
imageVector = Icons.Default.BarChart,
contentDescription = stringResource(R.string.histogram),
modifier = Modifier.size(20.dp).autoRotate(),
tint = if (showHistogram) Color.Yellow else Color.White
)
}
IconButton(onClick = onSettingsClick) {
Icon(
imageVector = Icons.Default.Settings,
contentDescription = stringResource(R.string.settings),
modifier = Modifier.size(20.dp).autoRotate(),
tint = Color.White
)
}
}
}
@Composable
private fun VideoTopBar(
isRecording: Boolean,
@@ -248,6 +359,14 @@ private fun VideoParameterCluster(
}
}
@Composable
private fun quickShotResolutionLabel(resolution: QuickShotResolutionPreset): String {
return when (resolution) {
QuickShotResolutionPreset.FULL -> stringResource(R.string.quick_shot_resolution_full)
else -> resolution.displayName
}
}
@Composable
private fun ParameterText(
text: String,
@@ -63,6 +63,9 @@ fun CameraTopSheet(
videoAudioInputId: String,
videoAudioInputOptions: List<VideoAudioInputOption>,
onVideoAudioInputChange: (String) -> Unit,
quickShotResolution: QuickShotResolutionPreset,
quickShotCapabilities: QuickShotCapabilities,
onQuickShotResolutionChange: (QuickShotResolutionPreset) -> Unit,
useRaw: Boolean,
onRawToggle: (Boolean) -> Unit,
isRawSupported: Boolean,
@@ -225,7 +228,7 @@ fun CameraTopSheet(
modifier = Modifier.weight(1f)
)
}
} else {
} else if (captureMode == CaptureMode.VIDEO) {
SectionLabel(title = stringResource(R.string.video_aspect_chip))
Row(
modifier = Modifier.fillMaxWidth(),
@@ -389,6 +392,89 @@ fun CameraTopSheet(
}
}
}
} else {
SectionLabel(title = stringResource(R.string.aspect_ratio))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
AspectRatio.sanitizeTopSheetRatios(topSheetAspectRatios).forEach { ratio ->
val isSelected = aspectRatio == ratio
Box(
modifier = Modifier
.weight(1f)
.height(40.dp)
.clip(RoundedCornerShape(8.dp))
.background(
if (isSelected) Color(0xFFFF6B35) else Color.White.copy(
alpha = 0.12f
)
)
.clickable { onAspectRatioChange(ratio) },
contentAlignment = Alignment.Center
) {
Text(
text = ratio.getDisplayName(),
color = if (isSelected) Color.Black else Color.White,
fontSize = 11.sp,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium
)
}
}
}
Spacer(modifier = Modifier.height(16.dp))
SectionLabel(title = stringResource(R.string.quick_shot_resolution_title))
FlowRow(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
val quickShotResolutions = quickShotCapabilities.availableResolutions
.ifEmpty { listOf(quickShotResolution) }
quickShotResolutions.forEach { resolution ->
VideoOptionChip(
title = quickShotResolutionLabel(resolution),
selected = quickShotResolution == resolution,
onClick = { onQuickShotResolutionChange(resolution) }
)
}
}
Spacer(modifier = Modifier.height(12.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
val meteringLabel = when (meteringMode) {
MeteringMode.SPOT -> stringResource(R.string.metering_spot)
MeteringMode.CENTER_WEIGHTED -> stringResource(R.string.metering_center_weighted)
MeteringMode.AVERAGE -> stringResource(R.string.metering_average)
MeteringMode.HIGHLIGHT_PRIORITY -> stringResource(R.string.metering_highlight_priority)
}
QuickSettingValue(
title = stringResource(R.string.metering_mode),
value = meteringLabel,
onClick = {
val next = when (meteringMode) {
MeteringMode.SPOT -> MeteringMode.CENTER_WEIGHTED
MeteringMode.CENTER_WEIGHTED -> MeteringMode.AVERAGE
MeteringMode.AVERAGE -> MeteringMode.HIGHLIGHT_PRIORITY
MeteringMode.HIGHLIGHT_PRIORITY -> MeteringMode.SPOT
}
onMeteringModeChange(next)
},
modifier = Modifier.weight(1f)
)
QuickSettingButton(
title = stringResource(R.string.toolbox_title),
icon = Icons.Default.Palette,
onClick = onToolboxClick,
modifier = Modifier.weight(1f)
)
}
}
Spacer(modifier = Modifier.height(16.dp))
@@ -705,6 +791,14 @@ private fun videoAspectRatioLabel(aspectRatio: VideoAspectRatio): String {
}
}
@Composable
private fun quickShotResolutionLabel(resolution: QuickShotResolutionPreset): String {
return when (resolution) {
QuickShotResolutionPreset.FULL -> stringResource(R.string.quick_shot_resolution_full)
else -> resolution.displayName
}
}
@Composable
private fun videoLogProfileLabel(profile: VideoLogProfile): String {
return when (profile) {
@@ -0,0 +1,162 @@
package com.hinnka.mycamera.video
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraCharacteristics
import android.util.Size
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.utils.PLog
import kotlin.math.abs
enum class QuickShotResolutionPreset(
val displayName: String,
val targetLongEdge: Int?
) {
FHD_1080P("1080p", 1920),
QHD_2K("2K", 2560),
UHD_4K("4K", 3840),
FULL("Full", null);
}
data class QuickShotConfig(
val resolution: QuickShotResolutionPreset = QuickShotResolutionPreset.FHD_1080P
)
data class QuickShotCapabilities(
val availableResolutions: List<QuickShotResolutionPreset> = emptyList(),
val previewSizesByResolution: Map<QuickShotResolutionPreset, Size> = emptyMap()
)
data class QuickShotCapabilitySnapshot(
val config: QuickShotConfig,
val capabilities: QuickShotCapabilities,
val previewSize: Size
)
data class QuickShotOutputSize(
val width: Int,
val height: Int
) {
val longEdge: Int
get() = maxOf(width, height)
val area: Long
get() = width.toLong() * height.toLong()
fun portraitAspectRatio(): Float {
val shortEdge = minOf(width, height).coerceAtLeast(1)
return shortEdge.toFloat() / longEdge.coerceAtLeast(1).toFloat()
}
fun toAndroidSize(): Size = Size(width, height)
}
data class QuickShotSizeSnapshot(
val config: QuickShotConfig,
val availableResolutions: List<QuickShotResolutionPreset>,
val previewSizesByResolution: Map<QuickShotResolutionPreset, QuickShotOutputSize>,
val previewSize: QuickShotOutputSize
)
object QuickShotCapabilitiesResolver {
private const val TAG = "QuickShotCapabilitiesResolver"
private val FALLBACK_SIZE = QuickShotOutputSize(1440, 1920)
fun resolve(
characteristics: CameraCharacteristics,
requestedConfig: QuickShotConfig,
aspectRatio: AspectRatio
): QuickShotCapabilitySnapshot {
val streamConfigMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
val previewOutputSizes = try {
streamConfigMap?.getOutputSizes(SurfaceTexture::class.java)
?.map { QuickShotOutputSize(it.width, it.height) }
.orEmpty()
} catch (e: Exception) {
PLog.w(TAG, "Failed to query quick-shot preview sizes: ${e.message}")
emptyList()
}
val sizeSnapshot = resolveFromOutputSizes(
outputSizes = previewOutputSizes,
requestedConfig = requestedConfig,
portraitAspectRatio = aspectRatio.getValue(isLandscape = false)
)
return QuickShotCapabilitySnapshot(
config = sizeSnapshot.config,
capabilities = QuickShotCapabilities(
availableResolutions = sizeSnapshot.availableResolutions,
previewSizesByResolution = sizeSnapshot.previewSizesByResolution.mapValues { it.value.toAndroidSize() }
),
previewSize = sizeSnapshot.previewSize.toAndroidSize()
)
}
fun resolveFromOutputSizes(
outputSizes: List<QuickShotOutputSize>,
requestedConfig: QuickShotConfig,
portraitAspectRatio: Float
): QuickShotSizeSnapshot {
val sanitizedSizes = outputSizes
.filter { it.width > 0 && it.height > 0 }
.distinct()
if (sanitizedSizes.isEmpty()) {
return QuickShotSizeSnapshot(
config = requestedConfig.copy(resolution = QuickShotResolutionPreset.FHD_1080P),
availableResolutions = listOf(QuickShotResolutionPreset.FHD_1080P),
previewSizesByResolution = mapOf(QuickShotResolutionPreset.FHD_1080P to FALLBACK_SIZE),
previewSize = FALLBACK_SIZE
)
}
val availableSizes = QuickShotResolutionPreset.entries.mapNotNull { preset ->
val size = findBestOutputSize(sanitizedSizes, preset, portraitAspectRatio)
size?.let { preset to it }
}
val availableResolutions = availableSizes.map { it.first }
val resolvedResolution = requestedConfig.resolution.takeIf { it in availableResolutions }
?: availableResolutions.firstOrNull()
?: QuickShotResolutionPreset.FHD_1080P
val previewSizesByResolution = availableSizes.toMap()
val previewSize = previewSizesByResolution[resolvedResolution]
?: findFullSize(sanitizedSizes, portraitAspectRatio)
?: FALLBACK_SIZE
return QuickShotSizeSnapshot(
config = requestedConfig.copy(resolution = resolvedResolution),
availableResolutions = availableResolutions.ifEmpty { listOf(resolvedResolution) },
previewSizesByResolution = previewSizesByResolution.ifEmpty { mapOf(resolvedResolution to previewSize) },
previewSize = previewSize
)
}
private fun findBestOutputSize(
outputSizes: List<QuickShotOutputSize>,
preset: QuickShotResolutionPreset,
portraitAspectRatio: Float
): QuickShotOutputSize? {
if (preset == QuickShotResolutionPreset.FULL) {
return findFullSize(outputSizes, portraitAspectRatio)
}
val targetLongEdge = preset.targetLongEdge ?: return null
return outputSizes
.filter { it.longEdge >= targetLongEdge }
.sortedWith(
compareBy<QuickShotOutputSize> { abs(it.portraitAspectRatio() - portraitAspectRatio) }
.thenBy { abs(it.longEdge - targetLongEdge) }
.thenBy { it.area }
)
.firstOrNull()
}
private fun findFullSize(
outputSizes: List<QuickShotOutputSize>,
portraitAspectRatio: Float
): QuickShotOutputSize? {
return outputSizes
.sortedWith(
compareByDescending<QuickShotOutputSize> { it.area }
.thenBy { abs(it.portraitAspectRatio() - portraitAspectRatio) }
)
.firstOrNull()
}
}
@@ -17,6 +17,7 @@ enum class VideoStabilizationMode(val displayName: String) {
enum class CaptureMode {
PHOTO,
QUICK_SHOT,
VIDEO
}
@@ -58,6 +58,7 @@ import com.hinnka.mycamera.ui.camera.CameraGLSurfaceView
import com.hinnka.mycamera.ui.camera.ZoomDisplayMode
import com.hinnka.mycamera.utils.*
import com.hinnka.mycamera.video.CaptureMode
import com.hinnka.mycamera.video.QuickShotResolutionPreset
import com.hinnka.mycamera.video.VideoAudioInputManager
import com.hinnka.mycamera.video.VideoAudioInputOption
import com.hinnka.mycamera.video.VideoAspectRatio
@@ -72,6 +73,7 @@ import kotlin.math.roundToInt
import kotlinx.coroutines.flow.*
import java.io.File
import java.util.UUID
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.abs
data class MultipleExposureFrame(
@@ -206,6 +208,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
private const val HDR_BRACKET_FRAME_COUNT = 3
private const val HDR_BRACKET_ZERO_INDEX = 0
private const val HDR_BRACKET_LOW_INDEX = 2
private const val QUICK_SHOT_BURST_MAX_PENDING_SAVES = 2
}
private data class HdrBracketFrame(
@@ -1095,6 +1098,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
private var burstPhotoId: String? = null
var burstImageCount by mutableStateOf(0)
private set
private var quickShotBurstActive = false
private var quickShotBurstCaptureInFlight = false
private val quickShotBurstPendingSaves = AtomicInteger(0)
var showGhostPermissions by mutableStateOf(false)
@@ -1203,6 +1209,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
if (currentCameraState.vendorCaptureSettingsByLens != it.vendorCaptureSettingsByLens) {
cameraController.setVendorCaptureSettingsByLens(it.vendorCaptureSettingsByLens)
}
if (currentCameraState.quickShotConfig.resolution != it.quickShotResolution) {
cameraController.setQuickShotResolution(it.quickShotResolution)
}
// 同步 RAW 设置到相机控制器
val multipleExposureEnabled = it.useMultipleExposure
val effectiveUseRaw = it.useRaw && !multipleExposureEnabled
@@ -1378,6 +1387,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
// 如果保存的值无效,使用默认值
}
cameraController.setCaptureMode(prefs.captureMode)
cameraController.setQuickShotResolution(prefs.quickShotResolution)
cameraController.setVideoResolution(prefs.videoResolution)
cameraController.setVideoFps(prefs.videoFps)
cameraController.setVideoAspectRatio(prefs.videoAspectRatio)
@@ -2076,6 +2086,11 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
fun capture() {
if (state.value.captureMode == CaptureMode.QUICK_SHOT) {
captureQuickShot()
return
}
if (state.value.captureMode == CaptureMode.VIDEO) {
if (state.value.videoRecordingState.isRecording) {
cameraController.stopVideoRecording()
@@ -2163,10 +2178,69 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
} ?: PLog.w(TAG, "captureVideoFrame skipped: glSurfaceView unavailable")
}
private fun captureQuickShot() {
val currentState = state.value
if (currentState.captureMode != CaptureMode.QUICK_SHOT || currentState.isCapturing) {
return
}
updateCaptureLocation()
if (isShutterSoundEnabled) {
shutterSoundPlayer.play()
}
if (isVibrationEnabled) {
vibrationHelper.vibrate()
}
val glView = glSurfaceView
if (glView == null) {
PLog.w(TAG, "captureQuickShot skipped: glSurfaceView unavailable")
return
}
cameraController.setQuickShotCaptureState(isCapturing = true)
glView.capturePreviewFrame(quickShotCaptureLongEdge()) { bitmap ->
cameraController.setQuickShotCaptureState(isCapturing = false)
viewModelScope.launch {
try {
savePreviewBitmapCapture(
bitmap = bitmap,
metadataCaptureMode = "quick_shot",
ratio = state.value.aspectRatio,
storeRenderedLookMetadata = false
)
} finally {
if (!bitmap.isRecycled) {
bitmap.recycle()
}
}
}
}
}
private fun updateCaptureLocation() {
if (userPreferences.value.saveLocation) {
val location = locationManager.getCurrentLocation()
cameraController.setLocation(location?.latitude, location?.longitude)
} else {
cameraController.setLocation(null, null)
}
}
private fun quickShotCaptureLongEdge(): Int {
val previewSize = state.value.currentPreviewSize
return maxOf(previewSize.width, previewSize.height).coerceAtLeast(1)
}
/**
* 开始连拍
*/
fun startContinuousCapture() {
if (state.value.captureMode == CaptureMode.QUICK_SHOT) {
startQuickShotBurst()
return
}
if (state.value.useRaw && state.value.isRawSupported) return
generateThumbnail()
burstImages.clear()
@@ -2185,6 +2259,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
* 停止连拍
*/
fun stopContinuousCapture() {
if (state.value.captureMode == CaptureMode.QUICK_SHOT) {
stopQuickShotBurst()
return
}
if (state.value.useRaw && state.value.isRawSupported) return
cameraController.stopBurstCapture()
shutterSoundPlayer.stopBurst()
@@ -2193,6 +2271,78 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
}
private fun startQuickShotBurst() {
if (quickShotBurstActive) return
updateCaptureLocation()
generateThumbnail()
burstImages.clear()
burstImageCount = 0
burstPhotoId = UUID.randomUUID().toString()
quickShotBurstPendingSaves.set(0)
quickShotBurstCaptureInFlight = false
quickShotBurstActive = true
cameraController.setQuickShotCaptureState(isCapturing = true, burstCapturing = true)
if (isShutterSoundEnabled) {
shutterSoundPlayer.playBurst()
}
requestNextQuickShotBurstFrame()
}
private fun stopQuickShotBurst() {
if (!quickShotBurstActive && !state.value.burstCapturing) return
quickShotBurstActive = false
quickShotBurstCaptureInFlight = false
cameraController.setQuickShotCaptureState(isCapturing = false, burstCapturing = false)
shutterSoundPlayer.stopBurst()
burstImageCount = 0
viewModelScope.launch {
_imageSavedEvent.emit(Unit)
}
}
private fun requestNextQuickShotBurstFrame() {
if (!quickShotBurstActive || quickShotBurstCaptureInFlight) return
val glView = glSurfaceView ?: run {
PLog.w(TAG, "Quick-shot burst stopped: glSurfaceView unavailable")
stopQuickShotBurst()
return
}
quickShotBurstCaptureInFlight = true
glView.captureNextPreviewFrame(quickShotCaptureLongEdge()) { bitmap ->
quickShotBurstCaptureInFlight = false
if (!quickShotBurstActive) {
if (!bitmap.isRecycled) {
bitmap.recycle()
}
return@captureNextPreviewFrame
}
val pendingSaveCount = quickShotBurstPendingSaves.incrementAndGet()
if (pendingSaveCount > QUICK_SHOT_BURST_MAX_PENDING_SAVES) {
quickShotBurstPendingSaves.decrementAndGet()
if (!bitmap.isRecycled) {
bitmap.recycle()
}
PLog.w(TAG, "Quick-shot burst frame dropped: pendingSaves=$pendingSaveCount")
requestNextQuickShotBurstFrame()
return@captureNextPreviewFrame
}
burstImageCount++
viewModelScope.launch {
try {
saveQuickShotBurstFrame(bitmap)
} finally {
if (!bitmap.isRecycled) {
bitmap.recycle()
}
quickShotBurstPendingSaves.decrementAndGet()
}
}
requestNextQuickShotBurstFrame()
}
}
/**
* 切换摄像头(前后置切换)
@@ -2366,7 +2516,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
fun setCaptureMode(mode: CaptureMode) {
if (state.value.videoRecordingState.isRecording && mode != state.value.captureMode) return
val shouldDisableVideoLog = mode == CaptureMode.PHOTO &&
val shouldDisableVideoLog = mode != CaptureMode.VIDEO &&
state.value.videoConfig.logProfile != VideoLogProfile.OFF
cameraController.setCaptureMode(mode)
currentSurfaceTexture = null
@@ -2387,6 +2537,14 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
}
fun setQuickShotResolution(resolution: QuickShotResolutionPreset) {
cameraController.setQuickShotResolution(resolution)
reopenCamera()
viewModelScope.launch {
userPreferencesRepository.saveQuickShotResolution(resolution)
}
}
fun setVideoFps(fps: VideoFpsPreset) {
cameraController.setVideoFps(fps)
reopenCamera()
@@ -4036,6 +4194,20 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
private suspend fun saveVideoSnapshot(bitmap: Bitmap) {
savePreviewBitmapCapture(
bitmap = bitmap,
metadataCaptureMode = "video_snapshot",
ratio = mapVideoAspectRatioToPhotoAspectRatio(state.value.videoConfig.aspectRatio),
storeRenderedLookMetadata = true
)
}
private suspend fun savePreviewBitmapCapture(
bitmap: Bitmap,
metadataCaptureMode: String,
ratio: AspectRatio?,
storeRenderedLookMetadata: Boolean
) {
try {
val context = getApplication<Application>()
val currentState = state.value
@@ -4047,7 +4219,11 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val userPrefs = userPreferencesRepository.userPreferences.firstOrNull()
val shouldMirror = cameraController.getLensFacing() == CameraCharacteristics.LENS_FACING_FRONT &&
(userPrefs?.mirrorFrontCamera ?: true)
val baselineMetadata = resolveBaselineMetadata(BaselineColorCorrectionTarget.JPG, userPrefs)
val baselineMetadata = if (storeRenderedLookMetadata) {
resolveBaselineMetadata(BaselineColorCorrectionTarget.JPG, userPrefs)
} else {
null
}
val currentCameraId = cameraController.getCurrentCameraId()
val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure(
userPrefs = userPrefs,
@@ -4057,9 +4233,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val spectralFilmSettings = resolveRawSpectralFilmSettings(userPrefs)
val metadata = MediaMetadata(
lutId = currentLutId.value,
frameId = currentFrameId,
colorRecipeParams = getMergedRecipeParams(),
lutId = if (storeRenderedLookMetadata) currentLutId.value else null,
frameId = if (storeRenderedLookMetadata) currentFrameId else null,
colorRecipeParams = if (storeRenderedLookMetadata) getMergedRecipeParams() else null,
baselineTarget = baselineMetadata?.first,
baselineLutId = baselineMetadata?.second,
baselineColorRecipeParams = baselineMetadata?.third,
@@ -4080,14 +4256,14 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawCfaCorrectionMode = userPrefs?.rawCfaCorrectionModes?.get(currentCameraId) ?: RawCfaCorrection.MODE_DEFAULT,
cameraId = currentCameraId,
rawColorEngine = userPrefs?.rawColorEngine ?: RawColorEngine.AdobeCurve,
spectralFilmStock = spectralFilmSettings.stock,
spectralFilmPrint = spectralFilmSettings.print,
spectralFilmCDensityGain = spectralFilmSettings.tuning.cDensityGain,
spectralFilmMDensityGain = spectralFilmSettings.tuning.mDensityGain,
spectralFilmYDensityGain = spectralFilmSettings.tuning.yDensityGain,
spectralFilmStock = if (storeRenderedLookMetadata) spectralFilmSettings.stock else null,
spectralFilmPrint = if (storeRenderedLookMetadata) spectralFilmSettings.print else null,
spectralFilmCDensityGain = if (storeRenderedLookMetadata) spectralFilmSettings.tuning.cDensityGain else 1f,
spectralFilmMDensityGain = if (storeRenderedLookMetadata) spectralFilmSettings.tuning.mDensityGain else 1f,
spectralFilmYDensityGain = if (storeRenderedLookMetadata) spectralFilmSettings.tuning.yDensityGain else 1f,
width = bitmap.width,
height = bitmap.height,
ratio = mapVideoAspectRatioToPhotoAspectRatio(currentState.videoConfig.aspectRatio),
ratio = ratio,
rotation = 0,
deviceModel = Build.MODEL,
brand = Build.MANUFACTURER,
@@ -4098,7 +4274,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
droMode = droMode.value,
isMirrored = shouldMirror,
dynamicRangeProfile = currentState.currentDynamicRangeProfile,
captureMode = "video_snapshot"
captureMode = metadataCaptureMode
)
val photoId = GalleryManager.preparePhoto(
@@ -4111,7 +4287,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
includeCropRegionInOutputSize = false
)
if (photoId == null) {
PLog.e(TAG, "Failed to prepare video snapshot")
PLog.e(TAG, "Failed to prepare preview bitmap capture: $metadataCaptureMode")
return
}
@@ -4128,10 +4304,108 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
photoQualityValue
)
}
PLog.d(TAG, "Video snapshot saved: $photoId")
PLog.d(TAG, "Preview bitmap capture saved: $photoId, mode=$metadataCaptureMode")
_imageSavedEvent.emit(Unit)
} catch (e: Exception) {
PLog.e(TAG, "Failed to save video snapshot", e)
PLog.e(TAG, "Failed to save preview bitmap capture: $metadataCaptureMode", e)
}
}
private suspend fun saveQuickShotBurstFrame(bitmap: Bitmap) {
try {
val context = getApplication<Application>()
val photoId = burstPhotoId ?: return
val currentState = state.value
val shouldAutoSave = autoSaveAfterCapture.firstOrNull() ?: false
val sharpeningValue = sharpening.firstOrNull() ?: 0f
val noiseReductionValue = noiseReduction.firstOrNull() ?: 0f
val chromaNoiseReductionValue = chromaNoiseReduction.firstOrNull() ?: 0f
val photoQualityValue = photoQuality.firstOrNull() ?: 95
val userPrefs = userPreferencesRepository.userPreferences.firstOrNull()
val shouldMirror = cameraController.getLensFacing() == CameraCharacteristics.LENS_FACING_FRONT &&
(userPrefs?.mirrorFrontCamera ?: true)
val currentCameraId = cameraController.getCurrentCameraId()
val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure(
userPrefs = userPrefs,
isRawCapture = false,
exposureBias = currentState.exposureBias,
)
if (GalleryManager.loadMetadata(context, photoId) == null) {
val metadata = MediaMetadata(
lutId = null,
frameId = null,
colorRecipeParams = null,
baselineTarget = null,
baselineLutId = null,
baselineColorRecipeParams = null,
sharpening = sharpeningValue,
noiseReduction = noiseReductionValue,
chromaNoiseReduction = chromaNoiseReductionValue,
rawDcpId = userPrefs?.rawDcpId,
rawDenoiseValue = userPrefs?.rawNlmNoiseFactor ?: 0f,
rawExposureCompensation = userPrefs?.rawExposureCompensation ?: 0f,
rawAutoExposure = effectiveRawAutoExposure,
rawHighlightsAdjustment = userPrefs?.rawHighlightsAdjustment ?: 0f,
rawShadowsAdjustment = userPrefs?.rawShadowsAdjustment ?: 0f,
rawBlackPointCorrection = userPrefs?.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = userPrefs?.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = userPrefs?.rawAutoWhiteBalanceEstimate ?: false,
rawBlackLevelMode = userPrefs?.rawBlackLevelModes?.get(currentCameraId) ?: "Default",
rawCustomBlackLevel = userPrefs?.rawCustomBlackLevels?.get(currentCameraId) ?: 0f,
rawCfaCorrectionMode = userPrefs?.rawCfaCorrectionModes?.get(currentCameraId) ?: RawCfaCorrection.MODE_DEFAULT,
cameraId = currentCameraId,
rawColorEngine = userPrefs?.rawColorEngine ?: RawColorEngine.AdobeCurve,
spectralFilmStock = null,
spectralFilmPrint = null,
spectralFilmCDensityGain = 1f,
spectralFilmMDensityGain = 1f,
spectralFilmYDensityGain = 1f,
width = bitmap.width,
height = bitmap.height,
ratio = currentState.aspectRatio,
rotation = 0,
deviceModel = Build.MODEL,
brand = Build.MANUFACTURER,
dateTaken = System.currentTimeMillis(),
latitude = currentState.latitude,
longitude = currentState.longitude,
exposureBias = currentState.exposureBias,
droMode = droMode.value,
isMirrored = shouldMirror,
dynamicRangeProfile = currentState.currentDynamicRangeProfile,
captureMode = "quick_shot"
)
val preparedPhotoId = GalleryManager.preparePhoto(
context,
metadata,
null,
bitmap,
false,
1.0f,
includeCropRegionInOutputSize = false,
photoId = photoId
)
if (preparedPhotoId == null) {
PLog.e(TAG, "Failed to prepare quick-shot burst photo")
return
}
}
GalleryManager.saveBitmapBurstPhoto(
context,
photoId,
bitmap,
shouldAutoSave,
contentRepository.photoProcessor,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQualityValue
)
} catch (e: Exception) {
PLog.e(TAG, "Failed to save quick-shot burst frame", e)
}
}
@@ -22,6 +22,9 @@
<string name="back">返回</string>
<string name="unknown">未知</string>
<string name="take_photo">拍照</string>
<string name="capture_mode_photo">拍照</string>
<string name="capture_mode_quick_shot">快拍</string>
<string name="capture_mode_video">视频</string>
<!-- Exposure Controls -->
@@ -40,6 +43,8 @@
<string name="settings_custom_aspect_ratio_width">宽</string>
<string name="settings_custom_aspect_ratio_height">高</string>
<string name="video_torch_chip">补光</string>
<string name="quick_shot_resolution_title">快拍分辨率</string>
<string name="quick_shot_resolution_full">全尺寸</string>
<string name="video_aspect_chip">画幅</string>
<string name="video_log_chip">Log</string>
<string name="video_option_off">关</string>
+5
View File
@@ -22,6 +22,9 @@
<string name="back">Back</string>
<string name="unknown">Unknown</string>
<string name="take_photo">Take Photo</string>
<string name="capture_mode_photo">Photo</string>
<string name="capture_mode_quick_shot">Quick Shot</string>
<string name="capture_mode_video">Video</string>
<!-- Exposure Controls -->
@@ -40,6 +43,8 @@
<string name="settings_custom_aspect_ratio_width">Width</string>
<string name="settings_custom_aspect_ratio_height">Height</string>
<string name="video_torch_chip">Torch</string>
<string name="quick_shot_resolution_title">Quick Shot Resolution</string>
<string name="quick_shot_resolution_full">Full</string>
<string name="video_aspect_chip">Aspect</string>
<string name="video_log_chip">Log</string>
<string name="video_option_off">Off</string>
@@ -0,0 +1,67 @@
package com.hinnka.mycamera.video
import org.junit.Assert.assertEquals
import org.junit.Test
class QuickShotCapabilitiesResolverTest {
@Test
fun resolveFromOutputSizes_prefersExactAspectAndTargetLongEdge() {
val snapshot = QuickShotCapabilitiesResolver.resolveFromOutputSizes(
outputSizes = listOf(
QuickShotOutputSize(1920, 1080),
QuickShotOutputSize(1920, 1440),
QuickShotOutputSize(2560, 1440),
QuickShotOutputSize(2560, 1920)
),
requestedConfig = QuickShotConfig(QuickShotResolutionPreset.QHD_2K),
portraitAspectRatio = 3f / 4f
)
assertEquals(QuickShotResolutionPreset.QHD_2K, snapshot.config.resolution)
assertEquals(QuickShotOutputSize(2560, 1920), snapshot.previewSize)
}
@Test
fun resolveFromOutputSizes_usesClosestLargerSizeWhenExactLongEdgeMissing() {
val snapshot = QuickShotCapabilitiesResolver.resolveFromOutputSizes(
outputSizes = listOf(
QuickShotOutputSize(1920, 1440),
QuickShotOutputSize(2688, 2016),
QuickShotOutputSize(3840, 2160)
),
requestedConfig = QuickShotConfig(QuickShotResolutionPreset.QHD_2K),
portraitAspectRatio = 3f / 4f
)
assertEquals(QuickShotResolutionPreset.QHD_2K, snapshot.config.resolution)
assertEquals(QuickShotOutputSize(2688, 2016), snapshot.previewSize)
}
@Test
fun resolveFromOutputSizes_fullUsesLargestSurfaceTextureSize() {
val snapshot = QuickShotCapabilitiesResolver.resolveFromOutputSizes(
outputSizes = listOf(
QuickShotOutputSize(1920, 1440),
QuickShotOutputSize(3840, 2160),
QuickShotOutputSize(4000, 3000)
),
requestedConfig = QuickShotConfig(QuickShotResolutionPreset.FULL),
portraitAspectRatio = 3f / 4f
)
assertEquals(QuickShotResolutionPreset.FULL, snapshot.config.resolution)
assertEquals(QuickShotOutputSize(4000, 3000), snapshot.previewSize)
}
@Test
fun resolveFromOutputSizes_fallsBackWhenRequestedPresetUnavailable() {
val snapshot = QuickShotCapabilitiesResolver.resolveFromOutputSizes(
outputSizes = listOf(QuickShotOutputSize(1280, 720)),
requestedConfig = QuickShotConfig(QuickShotResolutionPreset.UHD_4K),
portraitAspectRatio = 9f / 16f
)
assertEquals(QuickShotResolutionPreset.FULL, snapshot.config.resolution)
assertEquals(QuickShotOutputSize(1280, 720), snapshot.previewSize)
}
}