camera: improve all different camera modes
- Commit
a50f96bdf331505134ae5a75beed5872311b5d1a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-06-12 21:05 UTC (5 months ago)
- Parents
fb7fdf5
Diff
camera/build.gradle.kts
diff --git a/camera/build.gradle.kts b/camera/build.gradle.ktsindex 10d905c0c4..1e682b5b15 100644--- a/camera/build.gradle.kts+++ b/camera/build.gradle.kts@@ -6,6 +6,9 @@ android { defaultConfig { applicationId = "com.vayunmathur.camera" }+ packaging {+ jniLibs.useLegacyPackaging = true+ } } dependencies {@@ -13,6 +16,7 @@ dependencies { implementation(libs.androidx.camera.camera2) implementation(libs.androidx.camera.lifecycle) implementation(libs.androidx.camera.view)+ implementation(libs.androidx.camera.video) implementation(libs.zxing.core) implementation("com.google.mediapipe:tasks-vision:0.10.14") implementation("org.opencv:opencv:4.10.0")
camera/src/main/assets/deeplabv3.tflite
diff --git a/camera/src/main/assets/deeplabv3.tflite b/camera/src/main/assets/deeplabv3.tflitenew file mode 100644index 0000000000..420a934fdbBinary files /dev/null and b/camera/src/main/assets/deeplabv3.tflite differ
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.ktindex 8b523b4d27..60e12cb294 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -100,33 +100,59 @@ import com.vayunmathur.camera.util.FlashMode import com.vayunmathur.camera.util.QrAnalyzer import com.vayunmathur.camera.util.TimerDuration import com.vayunmathur.library.util.NavBackStack+import kotlinx.coroutines.delay -private val ZOOM_LEVELS = listOf(".5" to 0.5f, "1x" to 1f, "2" to 2f, "5" to 5f) private const val BOKEH_SHADER = """ uniform shader cameraInput; uniform shader alphaMask;- + half4 main(float2 fragCoord) { float maskAlpha = alphaMask.eval(fragCoord).a;- - if (maskAlpha > 0.5) {- return cameraInput.eval(fragCoord);- }- - half4 blur = half4(0.0);- float samples = 0.0;- - for (float x = -16.0; x <= 16.0; x += 2.0) {- for (float y = -16.0; y <= 16.0; y += 2.0) {- blur += cameraInput.eval(fragCoord + float2(x, y));- samples += 1.0;- }- }- half4 sharp = cameraInput.eval(fragCoord);- half4 blurred = blur / samples;- return mix(blurred, sharp, maskAlpha);++ // 3-pass separable bokeh: blur along 0°, 120°, 240° axes then average.+ // Each pass samples 13 taps along its direction (radius ~36px).+ float2 dir0 = float2(1.0, 0.0);+ float2 dir1 = float2(-0.5, 0.866);+ float2 dir2 = float2(-0.5, -0.866);++ // 1D Gaussian-ish weights for 13 taps (symmetric, sum ≈ 1)+ float w0 = 0.14;+ float w1 = 0.13;+ float w2 = 0.11;+ float w3 = 0.09;+ float w4 = 0.06;+ float w5 = 0.04;+ float w6 = 0.02;++ half4 pass0 = cameraInput.eval(fragCoord) * w0;+ half4 pass1 = cameraInput.eval(fragCoord) * w0;+ half4 pass2 = cameraInput.eval(fragCoord) * w0;++ for (float i = 1.0; i <= 6.0; i += 1.0) {+ float w;+ if (i < 1.5) w = w1;+ else if (i < 2.5) w = w2;+ else if (i < 3.5) w = w3;+ else if (i < 4.5) w = w4;+ else if (i < 5.5) w = w5;+ else w = w6;++ float2 off0 = dir0 * i * 6.0;+ float2 off1 = dir1 * i * 6.0;+ float2 off2 = dir2 * i * 6.0;++ pass0 += cameraInput.eval(fragCoord + off0) * w;+ pass0 += cameraInput.eval(fragCoord - off0) * w;+ pass1 += cameraInput.eval(fragCoord + off1) * w;+ pass1 += cameraInput.eval(fragCoord - off1) * w;+ pass2 += cameraInput.eval(fragCoord + off2) * w;+ pass2 += cameraInput.eval(fragCoord - off2) * w;+ }++ half4 blur = (pass0 + pass1 + pass2) / 3.0;+ return mix(blur, sharp, maskAlpha); } """ @@ -139,6 +165,7 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { val lensFacing by viewModel.lensFacing.collectAsState() val flashMode by viewModel.flashMode.collectAsState() val isRecording by viewModel.isRecording.collectAsState()+ val recordingDuration by viewModel.recordingDurationSec.collectAsState() val timerCountdown by viewModel.timerCountdown.collectAsState() val qrResult by viewModel.qrResult.collectAsState() val aspectRatio by viewModel.aspectRatio.collectAsState()@@ -153,6 +180,9 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { var maskBitmap by remember { mutableStateOf<android.graphics.Bitmap?>(null) } val isPhotoType = cameraMode in listOf(CameraMode.PHOTO, CameraMode.PORTRAIT, CameraMode.PANORAMA)+ val isSloMo = cameraMode == CameraMode.SLOW_MO+ val highSpeedActive by viewModel.highSpeedActive.collectAsState()+ val availableZoomLevels by viewModel.availableZoomLevels.collectAsState() val bokehShader = remember { lazy { RuntimeShader(BOKEH_SHADER) } } val panoSweeping by viewModel.panoramaEngine.isSweeping.collectAsState()@@ -160,11 +190,6 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { val panoFrameCount by viewModel.panoramaEngine.frameCount.collectAsState() val panoAngle by viewModel.panoramaEngine.sweepAngle.collectAsState() - val animatedZoom by animateFloatAsState(- targetValue = zoomRatio,- animationSpec = tween(durationMillis = 300)- )- // Orientation tracking var deviceRotation by remember { mutableIntStateOf(0) } val animatedRotation by animateFloatAsState(@@ -206,22 +231,42 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { .build() } + LaunchedEffect(lensFacing, isSloMo) {+ if (isSloMo) return@LaunchedEffect+ delay(500)+ viewModel.updateZoomLevels(lensFacing)+ }+ LaunchedEffect(Unit) { viewModel.updateLocation()- controller.isPinchToZoomEnabled = false+ controller.isPinchToZoomEnabled = true+ }++ // Sync controller's zoom state back to ViewModel (for pinch-to-zoom)+ DisposableEffect(controller, lifecycleOwner) {+ val observer = androidx.lifecycle.Observer<androidx.camera.core.ZoomState> { state ->+ if (state != null) {+ viewModel.setZoomRatio(state.zoomRatio)+ }+ }+ controller.zoomState.observe(lifecycleOwner, observer)+ onDispose { controller.zoomState.removeObserver(observer) } } LaunchedEffect(flashMode) { controller.imageCaptureFlashMode = viewModel.getImageCaptureFlashMode() } - LaunchedEffect(animatedZoom) {+ LaunchedEffect(zoomRatio) { val zoomState = controller.zoomState.value- if (zoomState != null) {- val clamped = animatedZoom.coerceIn(zoomState.minZoomRatio, zoomState.maxZoomRatio)- controller.setZoomRatio(clamped)- } else {- controller.setZoomRatio(animatedZoom)+ val currentZoom = zoomState?.zoomRatio ?: 0f+ if (kotlin.math.abs(currentZoom - zoomRatio) > 0.05f) {+ if (zoomState != null) {+ val clamped = zoomRatio.coerceIn(zoomState.minZoomRatio, zoomState.maxZoomRatio)+ controller.setZoomRatio(clamped)+ } else {+ controller.setZoomRatio(zoomRatio)+ } } } @@ -236,7 +281,11 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { } LaunchedEffect(cameraMode) {- if (cameraMode == CameraMode.PHOTO || cameraMode == CameraMode.PORTRAIT || cameraMode == CameraMode.PANORAMA) {+ if (cameraMode == CameraMode.SLOW_MO) {+ maskBitmap = null+ controller.clearImageAnalysisAnalyzer()+ viewModel.setQrResult(null)+ } else if (cameraMode == CameraMode.PHOTO || cameraMode == CameraMode.PORTRAIT || cameraMode == CameraMode.PANORAMA) { controller.setEnabledUseCases(CameraController.IMAGE_CAPTURE or CameraController.IMAGE_ANALYSIS) when (cameraMode) { CameraMode.PORTRAIT -> {@@ -270,11 +319,54 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { } } - DisposableEffect(Unit) {- controller.bindToLifecycle(lifecycleOwner)- onDispose { }+ // Manage camera binding: controller for normal modes, high-speed session for slo-mo+ val highSpeedPreviewView = remember {+ PreviewView(context).apply {+ scaleType = PreviewView.ScaleType.FILL_CENTER+ implementationMode = PreviewView.ImplementationMode.COMPATIBLE+ }+ }++ LaunchedEffect(isSloMo, lensFacing) {+ if (isSloMo) {+ controller.unbind()+ val success = viewModel.setupHighSpeedSession(+ lifecycleOwner,+ highSpeedPreviewView.surfaceProvider+ )+ if (!success) {+ android.util.Log.d("SloMo", "High-speed not available, falling back to CameraX")+ controller.bindToLifecycle(lifecycleOwner)+ val cameraControl = controller.cameraControl ?: return@LaunchedEffect+ val cam2Control = androidx.camera.camera2.interop.Camera2CameraControl.from(cameraControl)+ val cameraInfo = controller.cameraInfo ?: return@LaunchedEffect+ val cam2Info = androidx.camera.camera2.interop.Camera2CameraInfo.from(cameraInfo)+ val normalRanges = cam2Info.getCameraCharacteristic(+ android.hardware.camera2.CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES+ )+ val bestRange = normalRanges?.toList()?.filter { it.upper > 30 }?.maxByOrNull { it.upper }+ ?: android.util.Range(30, 30)+ viewModel.setSloMoFps(bestRange.upper)+ controller.videoCaptureQualitySelector =+ androidx.camera.video.QualitySelector.from(androidx.camera.video.Quality.HD)+ cam2Control.setCaptureRequestOptions(+ androidx.camera.camera2.interop.CaptureRequestOptions.Builder()+ .setCaptureRequestOption(+ android.hardware.camera2.CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE,+ bestRange+ )+ .build()+ )+ android.util.Log.d("SloMo", "Fallback: using ${bestRange.upper}fps via CameraX")+ }+ } else {+ viewModel.teardownHighSpeedSession()+ delay(200)+ controller.bindToLifecycle(lifecycleOwner)+ } } + val previewAspectRatio = when (aspectRatio) { AspectRatioOption.RATIO_16_9 -> 9f / 16f AspectRatioOption.RATIO_4_3 -> 3f / 4f@@ -308,33 +400,25 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { contentAlignment = Alignment.Center ) { @OptIn(ExperimentalComposeUiApi::class)- AndroidView(- factory = { ctx ->- PreviewView(ctx).apply {- this.controller = controller- scaleType = PreviewView.ScaleType.FIT_CENTER- implementationMode = PreviewView.ImplementationMode.COMPATIBLE- }- },- modifier = Modifier- .fillMaxWidth()- .aspectRatio(previewAspectRatio)- .clip(RoundedCornerShape(12.dp))- .then(- run {- val hasColorAdj = warmth != 0f || shadows != 0f- val hasBokeh = cameraMode == CameraMode.PORTRAIT && maskBitmap != null- if (hasBokeh || hasColorAdj) {- Modifier.graphicsLayer {- var effect: RenderEffect? = null-- if (hasBokeh) {- val mask = maskBitmap!!- val shader = bokehShader.value- val maskShader = BitmapShader(mask, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)- val matrix = Matrix()- matrix.setScale(size.width / mask.width, size.height / mask.height)- maskShader.setLocalMatrix(matrix)+ val previewModifier = Modifier+ .fillMaxWidth()+ .aspectRatio(previewAspectRatio)+ .clip(RoundedCornerShape(12.dp))+ .then(+ run {+ val hasColorAdj = warmth != 0f || shadows != 0f+ val hasBokeh = cameraMode == CameraMode.PORTRAIT && maskBitmap != null+ if (hasBokeh || hasColorAdj) {+ Modifier.graphicsLayer {+ var effect: RenderEffect? = null++ if (hasBokeh) {+ val mask = maskBitmap!!+ val shader = bokehShader.value+ val maskShader = BitmapShader(mask, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)+ val matrix = Matrix()+ matrix.setScale(size.width / mask.width, size.height / mask.height)+ maskShader.setLocalMatrix(matrix) shader.setInputShader("alphaMask", maskShader) effect = RenderEffect.createRuntimeShaderEffect(shader, "cameraInput") }@@ -364,18 +448,6 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { } } )- .pointerInput(Unit) {- detectTransformGestures { _, _, zoom, _ ->- val newZoom = (viewModel.zoomRatio.value * zoom)- val zoomState = controller.zoomState.value- val clamped = if (zoomState != null) {- newZoom.coerceIn(zoomState.minZoomRatio, zoomState.maxZoomRatio)- } else {- newZoom.coerceIn(0.5f, 10f)- }- viewModel.setZoomRatio(clamped)- }- } .pointerInteropFilter { event -> if (event.action == MotionEvent.ACTION_UP) { val factory = SurfaceOrientedMeteringPointFactory(@@ -387,7 +459,24 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { } false }- )++ if (isSloMo) {+ AndroidView(+ factory = { highSpeedPreviewView },+ modifier = previewModifier+ )+ } else {+ AndroidView(+ factory = { ctx ->+ PreviewView(ctx).apply {+ this.controller = controller+ scaleType = PreviewView.ScaleType.FIT_CENTER+ implementationMode = PreviewView.ImplementationMode.COMPATIBLE+ }+ },+ modifier = previewModifier+ )+ } if (gridEnabled) { GridOverlay(@@ -421,6 +510,7 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { ZoomBar( currentZoom = zoomRatio,+ zoomLevels = availableZoomLevels, onZoomSelected = { viewModel.setZoomRatio(it) }, modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 16.dp) )@@ -437,6 +527,7 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { if (panoSweeping) viewModel.stopPanorama() else viewModel.startPanorama() }+ isSloMo && highSpeedActive -> viewModel.toggleHighSpeedRecording() isPhotoType -> viewModel.takePhoto(controller) else -> viewModel.toggleRecording(controller) }@@ -460,6 +551,7 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { cameraMode = cameraMode, isPhotoType = isPhotoType, timerDuration = timerDuration,+ iconRotation = animatedRotation, onPickerChanged = { photo -> if (photo) { viewModel.setCameraMode(CameraMode.PHOTO)@@ -500,6 +592,13 @@ fun CameraScreen(backStack: NavBackStack<Route>, viewModel: CameraViewModel) { modifier = Modifier.align(Alignment.TopCenter).padding(top = 60.dp) ) }++ if (isRecording) {+ RecordingIndicator(+ durationSec = recordingDuration,+ modifier = Modifier.align(Alignment.TopCenter).padding(top = 60.dp)+ )+ } } } }@@ -685,7 +784,12 @@ private fun VerticalSlider( } @Composable-private fun ZoomBar(currentZoom: Float, onZoomSelected: (Float) -> Unit, modifier: Modifier = Modifier) {+private fun ZoomBar(+ currentZoom: Float,+ zoomLevels: List<Pair<String, Float>>,+ onZoomSelected: (Float) -> Unit,+ modifier: Modifier = Modifier+) { Row( modifier = modifier .background(Color(0x99000000), RoundedCornerShape(24.dp))@@ -693,8 +797,8 @@ private fun ZoomBar(currentZoom: Float, onZoomSelected: (Float) -> Unit, modifie horizontalArrangement = Arrangement.spacedBy(2.dp), verticalAlignment = Alignment.CenterVertically ) {- ZOOM_LEVELS.forEach { (label, ratio) ->- val isSelected = currentZoom == ratio+ zoomLevels.forEach { (label, ratio) ->+ val isSelected = kotlin.math.abs(currentZoom - ratio) < 0.05f Box( modifier = Modifier .size(36.dp)@@ -732,6 +836,10 @@ private fun ShutterRow( targetValue = if (isCapturing) 0.8f else 1f, animationSpec = spring(dampingRatio = 0.4f, stiffness = 800f) )+ val recordingCornerRadius by animateFloatAsState(+ targetValue = if (isRecording) 8f else 38f,+ animationSpec = spring(dampingRatio = 0.6f, stiffness = 500f)+ ) Row( modifier = Modifier@@ -765,19 +873,27 @@ private fun ShutterRow( } } + val animatedSize by animateFloatAsState(+ targetValue = if (isRecording) 36f else 66f,+ animationSpec = spring(dampingRatio = 0.6f, stiffness = 500f)+ ) Box( modifier = Modifier- .size((76 * shutterScale).dp)- .border(3.dp, Color.White, CircleShape)- .padding(5.dp)- .clip(CircleShape)- .background(- if (isRecording) Color.Red- else if (cameraMode in listOf(CameraMode.VIDEO, CameraMode.SLOW_MO, CameraMode.TIMELAPSE)) Color.Red- else Color.White- )- .clickable(onClick = onCapture)- )+ .size(76.dp)+ .border(3.dp, Color.White, CircleShape),+ contentAlignment = Alignment.Center+ ) {+ Box(+ modifier = Modifier+ .size(animatedSize.dp)+ .clip(RoundedCornerShape(recordingCornerRadius.dp))+ .background(+ if (cameraMode in listOf(CameraMode.VIDEO, CameraMode.SLOW_MO, CameraMode.TIMELAPSE)) Color.Red+ else Color.White+ )+ .clickable(onClick = onCapture)+ )+ } Box( modifier = Modifier@@ -844,6 +960,7 @@ private fun BottomBar( cameraMode: CameraMode, isPhotoType: Boolean, timerDuration: TimerDuration,+ iconRotation: Float, onPickerChanged: (Boolean) -> Unit, onSettingsClick: () -> Unit, onTimerCycle: () -> Unit@@ -866,7 +983,7 @@ private fun BottomBar( painterResource(com.vayunmathur.library.R.drawable.settings_24px), contentDescription = stringResource(R.string.settings), tint = Color.White,- modifier = Modifier.size(22.dp)+ modifier = Modifier.size(22.dp).rotate(iconRotation) ) } @@ -890,7 +1007,7 @@ private fun BottomBar( painterResource(R.drawable.photo_camera_24px), contentDescription = stringResource(R.string.mode_photo), tint = Color.White,- modifier = Modifier.size(20.dp)+ modifier = Modifier.size(20.dp).rotate(iconRotation) ) } Box(@@ -907,7 +1024,7 @@ private fun BottomBar( painterResource(R.drawable.video_camera_back_24px), contentDescription = stringResource(R.string.mode_video), tint = Color.White,- modifier = Modifier.size(20.dp)+ modifier = Modifier.size(20.dp).rotate(iconRotation) ) } }@@ -932,7 +1049,7 @@ private fun BottomBar( painterResource(R.drawable.ic_timer), contentDescription = stringResource(R.string.settings_timer), tint = Color.White,- modifier = Modifier.size(22.dp)+ modifier = Modifier.size(22.dp).rotate(iconRotation) ) } else { Column(horizontalAlignment = Alignment.CenterHorizontally) {@@ -940,7 +1057,7 @@ private fun BottomBar( painterResource(R.drawable.ic_timer), contentDescription = null, tint = Color.White,- modifier = Modifier.size(14.dp)+ modifier = Modifier.size(14.dp).rotate(iconRotation) ) Text(timerLabel, color = Color.White, fontSize = 10.sp, fontWeight = FontWeight.Bold, lineHeight = 10.sp) }@@ -997,6 +1114,39 @@ private fun QrResultOverlay(text: String, onDismiss: () -> Unit, context: Contex } } +@Composable+private fun RecordingIndicator(durationSec: Long, modifier: Modifier = Modifier) {+ val dotAlpha by animateFloatAsState(+ targetValue = if ((durationSec % 2) == 0L) 1f else 0.3f,+ animationSpec = tween(500)+ )++ val minutes = durationSec / 60+ val seconds = durationSec % 60+ val timeText = "%d:%02d".format(minutes, seconds)++ Row(+ modifier = modifier+ .background(Color(0xCC000000), RoundedCornerShape(20.dp))+ .padding(horizontal = 16.dp, vertical = 8.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ Box(+ modifier = Modifier+ .size(10.dp)+ .graphicsLayer { alpha = dotAlpha }+ .background(Color.Red, CircleShape)+ )+ Text(+ text = timeText,+ color = Color.White,+ fontSize = 16.sp,+ fontWeight = FontWeight.Bold+ )+ }+}+ @Composable private fun PanoramaOverlay( isSweeping: Boolean,
camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.ktindex 5971c91b2a..752d0bb5f4 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt@@ -11,39 +11,62 @@ import com.google.mediapipe.tasks.core.BaseOptions import com.google.mediapipe.tasks.vision.core.RunningMode import com.google.mediapipe.tasks.vision.imagesegmenter.ImageSegmenter +private const val PERSON_CLASS = 15 // "person" in DeepLabV3's 21-class Pascal VOC labels+private const val TEMPORAL_WEIGHT = 0.35f+ class BokehAnalyzer( context: Context, private val onMaskGenerated: (Bitmap) -> Unit ) : ImageAnalysis.Analyzer { + private var prevMask: FloatArray? = null private val imageSegmenter: ImageSegmenter init { val baseOptions = BaseOptions.builder()- .setModelAssetPath("selfie_segmenter.tflite")+ .setModelAssetPath("deeplabv3.tflite") .build() val options = ImageSegmenter.ImageSegmenterOptions.builder() .setBaseOptions(baseOptions) .setRunningMode(RunningMode.LIVE_STREAM)- .setOutputCategoryMask(false)- .setOutputConfidenceMasks(true)+ .setOutputCategoryMask(true)+ .setOutputConfidenceMasks(false) .setResultListener { result, _ ->- val masks = result.confidenceMasks()- if (masks.isPresent && masks.get().isNotEmpty()) {- val mpImage = masks.get()[0]- val w = mpImage.width- val h = mpImage.height- val floatBuffer = ByteBufferExtractor.extract(mpImage).asFloatBuffer()- floatBuffer.rewind()- val pixels = IntArray(w * h)- for (i in pixels.indices) {- val alpha = (floatBuffer.get().coerceIn(0f, 1f) * 255).toInt()- pixels[i] = Color.argb(alpha, 255, 255, 255)+ val catMask = result.categoryMask()+ if (!catMask.isPresent) return@setResultListener++ val mpImage = catMask.get()+ val w = mpImage.width+ val h = mpImage.height+ val buffer = ByteBufferExtractor.extract(mpImage)+ buffer.rewind()++ val current = FloatArray(w * h)+ for (i in current.indices) {+ val label = buffer.get().toInt() and 0xFF+ current[i] = if (label == PERSON_CLASS) 1f else 0f+ }++ // Temporal smoothing: blend with previous frame+ val prev = prevMask+ val smoothed = if (prev != null && prev.size == current.size) {+ FloatArray(current.size) { i ->+ current[i] * (1f - TEMPORAL_WEIGHT) + prev[i] * TEMPORAL_WEIGHT }- val maskBitmap = Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888)- onMaskGenerated(maskBitmap)+ } else current+ prevMask = smoothed++ // Gaussian blur the mask for soft edges+ val blurred = blurMask(smoothed, w, h)++ val pixels = IntArray(w * h)+ for (i in pixels.indices) {+ val alpha = (blurred[i].coerceIn(0f, 1f) * 255).toInt()+ pixels[i] = Color.argb(alpha, 255, 255, 255) }+ val maskBitmap = Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888)+ onMaskGenerated(maskBitmap) } .build() @@ -61,4 +84,31 @@ class BokehAnalyzer( fun close() { imageSegmenter.close() }++ private fun blurMask(src: FloatArray, w: Int, h: Int): FloatArray {+ // Two-pass separable Gaussian blur (radius 3, sigma ~1.5)+ val kernel = floatArrayOf(0.06f, 0.12f, 0.18f, 0.28f, 0.18f, 0.12f, 0.06f)+ val r = 3+ val temp = FloatArray(w * h)+ // Horizontal pass+ for (y in 0 until h) for (x in 0 until w) {+ var sum = 0f+ for (k in -r..r) {+ val sx = (x + k).coerceIn(0, w - 1)+ sum += src[y * w + sx] * kernel[k + r]+ }+ temp[y * w + x] = sum+ }+ // Vertical pass+ val dst = FloatArray(w * h)+ for (y in 0 until h) for (x in 0 until w) {+ var sum = 0f+ for (k in -r..r) {+ val sy = (y + k).coerceIn(0, h - 1)+ sum += temp[sy * w + x] * kernel[k + r]+ }+ dst[y * w + x] = sum+ }+ return dst+ } }
camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.ktindex f3e2a551ea..0560c71306 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -5,28 +5,42 @@ import android.content.ContentValues import android.content.Context import android.location.Location import android.location.LocationManager+import android.media.MediaMetadataRetriever import android.net.Uri import android.os.Environment import android.provider.MediaStore+import android.util.Log import androidx.camera.core.CameraSelector import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCaptureException+import androidx.camera.core.Preview+import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.video.FileOutputOptions+import androidx.camera.video.HighSpeedVideoSessionConfig+import androidx.camera.video.MediaStoreOutputOptions+import androidx.camera.video.Quality+import androidx.camera.video.QualitySelector+import androidx.camera.video.Recorder import androidx.camera.video.Recording+import androidx.camera.video.VideoCapture import androidx.camera.video.VideoRecordEvent import androidx.camera.view.CameraController import androidx.camera.view.LifecycleCameraController import androidx.camera.view.video.AudioConfig+import androidx.core.content.ContextCompat import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.viewModelScope import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch+import androidx.camera.lifecycle.awaitInstance import java.text.SimpleDateFormat import java.util.Date import java.util.Locale+import kotlin.math.roundToInt enum class CameraMode { PHOTO, PORTRAIT, PANORAMA, VIDEO, SLOW_MO, TIMELAPSE } enum class FlashMode { ON, OFF, AUTO }@@ -54,6 +68,10 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { private val _isRecording = MutableStateFlow(false) val isRecording = _isRecording.asStateFlow() + private val _recordingDurationSec = MutableStateFlow(0L)+ val recordingDurationSec = _recordingDurationSec.asStateFlow()+ private var recordingTimerJob: kotlinx.coroutines.Job? = null+ private val _timerCountdown = MutableStateFlow(0) val timerCountdown = _timerCountdown.asStateFlow() @@ -63,6 +81,9 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { private val _zoomRatio = MutableStateFlow(1f) val zoomRatio = _zoomRatio.asStateFlow() + private val _availableZoomLevels = MutableStateFlow(listOf("1x" to 1f))+ val availableZoomLevels = _availableZoomLevels.asStateFlow()+ private val _isCapturing = MutableStateFlow(false) val isCapturing = _isCapturing.asStateFlow() @@ -86,9 +107,23 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { private var lastLocation: Location? = null private var currentRecording: Recording? = null+ private var sloMoFps: Int = 30 val panoramaEngine = PanoramaEngine(app) + // High-speed session state+ private var cameraProvider: ProcessCameraProvider? = null+ private var highSpeedVideoCapture: VideoCapture<Recorder>? = null+ private var highSpeedRecording: Recording? = null+ private var highSpeedCamera: androidx.camera.core.Camera? = null++ private val _highSpeedActive = MutableStateFlow(false)+ val highSpeedActive = _highSpeedActive.asStateFlow()++ fun setSloMoFps(fps: Int) {+ sloMoFps = fps+ }+ init { loadSettings() }@@ -159,6 +194,25 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { fun setZoomRatio(ratio: Float) { _zoomRatio.value = ratio+ highSpeedCamera?.cameraControl?.setZoomRatio(ratio)+ }++ suspend fun updateZoomLevels(lensFacing: Int) {+ _availableZoomLevels.value = if (lensFacing == CameraSelector.LENS_FACING_BACK) {+ listOf(".5" to 0.5f, "1x" to 1f, "2x" to 2f, "5x" to 5f)+ } else {+ listOf(".7" to 0.7f, "1x" to 1f)+ }+ }++ private fun formatZoomLabel(ratio: Float): String {+ val tenths = (ratio * 10f).roundToInt()+ return when {+ tenths < 10 -> ".${tenths}"+ tenths == 10 -> "1x"+ tenths % 10 == 0 -> "${tenths / 10}"+ else -> "${tenths / 10}.${tenths % 10}"+ } } @android.annotation.SuppressLint("MissingPermission")@@ -171,6 +225,150 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { } catch (_: Exception) { } } + // --- High-speed session management ---++ suspend fun setupHighSpeedSession(+ lifecycleOwner: LifecycleOwner,+ surfaceProvider: Preview.SurfaceProvider+ ): Boolean {+ return try {+ val provider = ProcessCameraProvider.awaitInstance(app)+ cameraProvider = provider+ provider.unbindAll()++ val selector = CameraSelector.Builder()+ .requireLensFacing(_lensFacing.value)+ .build()++ val cameraInfo = provider.getCameraInfo(selector)+ val capabilities = Recorder.getHighSpeedVideoCapabilities(cameraInfo)+ if (capabilities == null) {+ Log.d("SloMo", "High-speed video not supported by this camera")+ return false+ }++ val supportedQualities = capabilities.getSupportedQualities(+ androidx.camera.core.DynamicRange.SDR+ )+ Log.d("SloMo", "High-speed supported qualities: $supportedQualities")++ val preview = Preview.Builder().build()+ preview.surfaceProvider = surfaceProvider++ val recorder = Recorder.Builder().build()+ val videoCapture = VideoCapture.withOutput(recorder)+ highSpeedVideoCapture = videoCapture++ val configBuilder = HighSpeedVideoSessionConfig.Builder(videoCapture)+ .setPreview(preview)+ .setSlowMotionEnabled(true)++ val ranges = cameraInfo.getSupportedFrameRateRanges(configBuilder.build())+ Log.d("SloMo", "High-speed supported frame rate ranges: $ranges")++ val bestRange = ranges.maxByOrNull { it.upper }+ if (bestRange == null) {+ Log.e("SloMo", "No high-speed frame rate ranges available")+ return false+ }++ configBuilder.setFrameRateRange(bestRange)+ sloMoFps = bestRange.upper+ Log.d("SloMo", "High-speed session configured at ${bestRange.upper}fps, slow-mo baked in")++ highSpeedCamera = provider.bindToLifecycle(lifecycleOwner, selector, configBuilder.build())++ // Set anti-banding to reduce flicker under artificial light+ try {+ val cam2Control = androidx.camera.camera2.interop.Camera2CameraControl.from(+ highSpeedCamera!!.cameraControl+ )+ cam2Control.setCaptureRequestOptions(+ androidx.camera.camera2.interop.CaptureRequestOptions.Builder()+ .setCaptureRequestOption(+ android.hardware.camera2.CaptureRequest.CONTROL_AE_ANTIBANDING_MODE,+ android.hardware.camera2.CameraMetadata.CONTROL_AE_ANTIBANDING_MODE_AUTO+ )+ .build()+ )+ } catch (e: Exception) {+ Log.w("SloMo", "Could not set anti-banding", e)+ }++ highSpeedCamera?.cameraInfo?.let { updateZoomLevels(_lensFacing.value) }+ _highSpeedActive.value = true+ true+ } catch (e: Exception) {+ Log.e("SloMo", "Failed to set up high-speed session", e)+ false+ }+ }++ fun teardownHighSpeedSession() {+ highSpeedRecording?.stop()+ highSpeedRecording = null+ cameraProvider?.unbindAll()+ highSpeedVideoCapture = null+ highSpeedCamera = null+ cameraProvider = null+ _highSpeedActive.value = false+ }++ @android.annotation.SuppressLint("MissingPermission")+ fun toggleHighSpeedRecording() {+ val videoCapture = highSpeedVideoCapture ?: return++ if (_isRecording.value) {+ highSpeedRecording?.stop()+ highSpeedRecording = null+ _isRecording.value = false+ recordingTimerJob?.cancel()+ _recordingDurationSec.value = 0+ return+ }++ val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())+ val contentValues = ContentValues().apply {+ put(MediaStore.MediaColumns.DISPLAY_NAME, "SLOMO_$timestamp")+ put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4")+ put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/Camera")+ }++ val outputOptions = MediaStoreOutputOptions.Builder(+ app.contentResolver,+ MediaStore.Video.Media.EXTERNAL_CONTENT_URI+ ).setContentValues(contentValues).build()++ _isRecording.value = true+ _recordingDurationSec.value = 0+ recordingTimerJob = viewModelScope.launch {+ while (true) {+ delay(1000)+ _recordingDurationSec.value += 1+ }+ }++ Log.d("SloMo", "Starting high-speed recording at ${sloMoFps}fps")++ highSpeedRecording = videoCapture.output+ .prepareRecording(app, outputOptions)+ .start(ContextCompat.getMainExecutor(app)) { event ->+ if (event is VideoRecordEvent.Finalize) {+ _isRecording.value = false+ recordingTimerJob?.cancel()+ _recordingDurationSec.value = 0+ if (event.hasError()) {+ Log.e("SloMo", "Recording error: ${event.error} - ${event.cause?.message}")+ } else {+ Log.d("SloMo", "High-speed recording saved: ${event.outputResults.outputUri}")+ setLastCaptureUri(event.outputResults.outputUri)+ }+ }+ }+ }++ // --- Standard recording ---+ fun takePhoto(controller: LifecycleCameraController) { val timer = _timerDuration.value if (timer.seconds > 0) {@@ -210,7 +408,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { controller.takePicture( outputOptions,- androidx.core.content.ContextCompat.getMainExecutor(app),+ ContextCompat.getMainExecutor(app), object : ImageCapture.OnImageSavedCallback { override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) { _isCapturing.value = false@@ -229,6 +427,8 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { currentRecording?.stop() currentRecording = null _isRecording.value = false+ recordingTimerJob?.cancel()+ _recordingDurationSec.value = 0 return } @@ -250,19 +450,48 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { val recordingMode = _cameraMode.value _isRecording.value = true+ _recordingDurationSec.value = 0+ recordingTimerJob = viewModelScope.launch {+ while (true) {+ delay(1000)+ _recordingDurationSec.value += 1+ }+ } currentRecording = controller.startRecording( outputOptions, AudioConfig.create(recordingMode == CameraMode.VIDEO),- androidx.core.content.ContextCompat.getMainExecutor(app)+ ContextCompat.getMainExecutor(app) ) { event -> if (event is VideoRecordEvent.Finalize) { _isRecording.value = false+ recordingTimerJob?.cancel()+ _recordingDurationSec.value = 0 viewModelScope.launch(kotlinx.coroutines.Dispatchers.IO) { if (!cacheFile.exists()) return@launch val fileToSave = when (recordingMode) { CameraMode.SLOW_MO -> { val processed = java.io.File(app.cacheDir, "SLOMO_$timestamp.mp4")- VideoProcessor.adjustSpeed(cacheFile, processed, 0.25f)+ val actualFps = try {+ val retriever = MediaMetadataRetriever()+ retriever.setDataSource(cacheFile.path)+ val frameCount = retriever.extractMetadata(+ MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT+ )?.toLongOrNull() ?: 0L+ val durationMs = retriever.extractMetadata(+ MediaMetadataRetriever.METADATA_KEY_DURATION+ )?.toLongOrNull() ?: 0L+ retriever.release()+ val detected = if (durationMs > 0) (frameCount * 1000f / durationMs) else sloMoFps.toFloat()+ Log.d("SloMo", "Fallback: ${frameCount} frames, ${durationMs}ms, detected=${detected}fps")+ detected+ } catch (e: Exception) {+ Log.e("SloMo", "Failed to detect FPS", e)+ sloMoFps.toFloat()+ }+ val effectiveFps = maxOf(actualFps, sloMoFps.toFloat())+ val speedFactor = 30f / effectiveFps+ Log.d("SloMo", "Fallback slowing: effectiveFps=$effectiveFps, speedFactor=$speedFactor")+ VideoProcessor.adjustSpeed(cacheFile, processed, speedFactor) cacheFile.delete() processed }
camera/src/main/java/com/vayunmathur/camera/util/VideoProcessor.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/VideoProcessor.kt b/camera/src/main/java/com/vayunmathur/camera/util/VideoProcessor.ktindex 18ae295511..e9b760b34d 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/VideoProcessor.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/VideoProcessor.kt@@ -3,16 +3,24 @@ package com.vayunmathur.camera.util import android.media.MediaCodec import android.media.MediaExtractor import android.media.MediaFormat+import android.media.MediaMetadataRetriever import android.media.MediaMuxer import java.io.File import java.nio.ByteBuffer object VideoProcessor { fun adjustSpeed(inputFile: File, outputFile: File, speedFactor: Float) {+ val retriever = MediaMetadataRetriever()+ val rotation = try {+ retriever.setDataSource(inputFile.path)+ retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)?.toIntOrNull() ?: 0+ } catch (_: Exception) { 0 } finally { retriever.release() }+ val extractor = MediaExtractor() extractor.setDataSource(inputFile.path) val muxer = MediaMuxer(outputFile.path, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)+ muxer.setOrientationHint(rotation) var videoTrackIndex = -1 var muxerTrackIndex = -1@@ -38,17 +46,40 @@ object VideoProcessor { val buffer = ByteBuffer.allocate(2 * 1024 * 1024) val info = MediaCodec.BufferInfo() + // Collect all sample timestamps first for smooth interpolation+ val samples = mutableListOf<Triple<Long, Int, Int>>() // timestamp, size, flags+ val dataChunks = mutableListOf<ByteArray>() while (true) { val size = extractor.readSampleData(buffer, 0) if (size < 0) break+ val chunk = ByteArray(size)+ buffer.position(0)+ buffer.get(chunk, 0, size)+ dataChunks.add(chunk)+ samples.add(Triple(extractor.sampleTime, size, extractor.sampleFlags))+ extractor.advance()+ }++ // Write with evenly distributed timestamps to avoid jitter at boundaries+ val totalDuration = if (samples.isNotEmpty()) samples.last().first else 0L+ val outputDuration = (totalDuration / speedFactor).toLong() + for (i in samples.indices) {+ val (originalPts, size, flags) = samples[i]+ val chunk = dataChunks[i]++ // Linearly remap timestamps for perfectly even spacing+ val normalizedPosition = if (totalDuration > 0) originalPts.toDouble() / totalDuration else 0.0+ val newPts = (normalizedPosition * outputDuration).toLong()++ buffer.clear()+ buffer.put(chunk) info.size = size- info.flags = extractor.sampleFlags- info.presentationTimeUs = (extractor.sampleTime / speedFactor).toLong()+ info.flags = flags+ info.presentationTimeUs = newPts info.offset = 0 muxer.writeSampleData(muxerTrackIndex, buffer, info)- extractor.advance() } muxer.stop()