Unify Android photo and video capture with explicit cache ownership
This commit is contained in:
1 parent
38b9bec498
commit
b2d4a002ef
3 files changed
+325
-768
No files matched your search
+325
@@ -0,0 +1,325 @@
|
||||
package com.utun.chat.ui.screens
|
||||
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Size
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.camera.core.*
|
||||
import androidx.camera.core.resolutionselector.ResolutionSelector
|
||||
import androidx.camera.core.resolutionselector.ResolutionStrategy
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
import androidx.camera.video.*
|
||||
import androidx.camera.view.PreviewView
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.*
|
||||
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.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.utun.chat.R
|
||||
import com.utun.chat.data.*
|
||||
import com.utun.chat.ui.components.ZoomableImage
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
|
||||
enum class CaptureMode { PHOTO, VIDEO }
|
||||
private enum class CapturePhase { IDLE, CAPTURING, RECORDING, PAUSED, FINALIZING, CAPTURED, SENDING }
|
||||
private enum class CaptureQuality(val label: String, val quality: Quality, val bitrate: Int) {
|
||||
SD_LOW("480p 512k", Quality.SD, 512_000), SD("480p 1M", Quality.SD, 1_000_000),
|
||||
HD("720p 2M", Quality.HD, 2_000_000), FHD("1080p 4.5M", Quality.FHD, 4_500_000)
|
||||
}
|
||||
|
||||
/** Одна камера и один владелец cache-файла; одновременно привязан только выбранный фото/видеозахват. */
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun CameraRecordScreen(initialMode: CaptureMode, onSend: (String, CaptureMode) -> Unit, onClose: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val lifecycle = LocalLifecycleOwner.current
|
||||
val main = remember(context) { ContextCompat.getMainExecutor(context) }
|
||||
val send by rememberUpdatedState(onSend)
|
||||
var mode by remember { mutableStateOf(initialMode) }
|
||||
var phase by remember { mutableStateOf(CapturePhase.IDLE) }
|
||||
var closed by remember { mutableStateOf(false) }
|
||||
var output by remember { mutableStateOf<File?>(null) }
|
||||
var recording by remember { mutableStateOf<Recording?>(null) }
|
||||
var pendingSend by remember { mutableStateOf(false) }
|
||||
var elapsed by remember { mutableStateOf(0L) }
|
||||
var error by remember { mutableStateOf(false) }
|
||||
var provider by remember { mutableStateOf<ProcessCameraProvider?>(null) }
|
||||
var camera by remember { mutableStateOf<Camera?>(null) }
|
||||
var lenses by remember { mutableStateOf<List<LensOption>>(emptyList()) }
|
||||
var lens by remember { mutableStateOf<LensOption?>(null) }
|
||||
var resolutions by remember { mutableStateOf<List<PhotoResolution>>(emptyList()) }
|
||||
var resolution by remember { mutableStateOf<PhotoResolution?>(null) }
|
||||
var quality by remember { mutableStateOf(CaptureQuality.HD) }
|
||||
var torch by remember { mutableStateOf(false) }
|
||||
var bitmap by remember(output) { mutableStateOf<Bitmap?>(null) }
|
||||
var photoSize by remember(output) { mutableStateOf(0 to 0) }
|
||||
var hasCamera by remember { mutableStateOf(ContextCompat.checkSelfPermission(context,
|
||||
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) }
|
||||
var hasAudio by remember { mutableStateOf(ContextCompat.checkSelfPermission(context,
|
||||
Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) }
|
||||
val cameraPermission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {
|
||||
hasCamera = it; LogManager.addLog(if (it) "INFO" else "WARN", "Capture", "Camera permission granted=$it")
|
||||
}
|
||||
val audioPermission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {
|
||||
hasAudio = it; LogManager.addLog(if (it) "INFO" else "WARN", "Capture", "Microphone permission granted=$it")
|
||||
}
|
||||
LaunchedEffect(Unit) { if (!hasCamera) cameraPermission.launch(Manifest.permission.CAMERA) }
|
||||
LaunchedEffect(mode, hasCamera) {
|
||||
if (mode == CaptureMode.VIDEO && hasCamera && !hasAudio) audioPermission.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
val preview = remember { Preview.Builder().build() }
|
||||
val imageCapture = remember(resolution) {
|
||||
ImageCapture.Builder().setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY).apply {
|
||||
resolution?.let { setResolutionSelector(ResolutionSelector.Builder().setResolutionStrategy(
|
||||
ResolutionStrategy(Size(it.width, it.height), ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER)).build()) }
|
||||
}.build()
|
||||
}
|
||||
val videoCapture = remember(quality) {
|
||||
VideoCapture.withOutput(Recorder.Builder().setQualitySelector(QualitySelector.from(quality.quality))
|
||||
.setTargetVideoEncodingBitRate(quality.bitrate).build())
|
||||
}
|
||||
|
||||
fun deleteCache(file: File?) {
|
||||
if (file != null && !file.delete() && file.exists()) LogManager.addLog("ERROR", "Capture", "Cannot delete cache ${file.path}")
|
||||
}
|
||||
fun reset() {
|
||||
val oldRecording = recording
|
||||
recording = null
|
||||
val oldFile = output
|
||||
output = null; pendingSend = false; elapsed = 0; phase = CapturePhase.IDLE
|
||||
oldRecording?.close()
|
||||
deleteCache(oldFile)
|
||||
LogManager.addLog("INFO", "Capture", "Capture discarded mode=$mode")
|
||||
}
|
||||
fun sendResult() {
|
||||
val file = output ?: return
|
||||
if (phase != CapturePhase.CAPTURED || file.length() <= 0) {
|
||||
LogManager.addLog("ERROR", "Capture", "Cannot send phase=$phase path=${file.path} bytes=${file.length()}")
|
||||
error = true; return
|
||||
}
|
||||
output = null; phase = CapturePhase.SENDING
|
||||
LogManager.addLog("INFO", "Capture", "Handing cache to sender mode=$mode path=${file.path} bytes=${file.length()}")
|
||||
send(file.path, mode)
|
||||
}
|
||||
BackHandler { reset(); onClose() }
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
onDispose {
|
||||
closed = true
|
||||
recording?.close(); recording = null
|
||||
provider?.unbindAll(); provider = null
|
||||
deleteCache(output); output = null
|
||||
LogManager.addLog("INFO", "Capture", "Camera released mode=$mode phase=$phase")
|
||||
}
|
||||
}
|
||||
LaunchedEffect(hasCamera) {
|
||||
if (hasCamera) {
|
||||
val future = ProcessCameraProvider.getInstance(context)
|
||||
future.addListener({
|
||||
if (!closed) try {
|
||||
val ready = future.get()
|
||||
lenses = CameraLensManager.enumerate(ready)
|
||||
lens = lenses.firstOrNull { it.type == LensType.SELFIE } ?: lenses.firstOrNull()
|
||||
provider = ready
|
||||
if (lens == null) { error = true; LogManager.addLog("ERROR", "Capture", "No available cameras") }
|
||||
} catch (e: Exception) {
|
||||
error = true; LogManager.addLog("ERROR", "Capture", "Provider initialization failed: ${e.message}")
|
||||
}
|
||||
}, main)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(provider, lens) {
|
||||
val ready = provider; val selected = lens
|
||||
if (ready != null && selected != null) {
|
||||
resolutions = CameraLensManager.photoResolutions(ready, selected.cameraId)
|
||||
resolution = resolutions.lastOrNull()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(provider, lens, mode, resolution, quality, hasAudio, phase == CapturePhase.IDLE) {
|
||||
if (phase != CapturePhase.IDLE) return@LaunchedEffect
|
||||
val ready = provider ?: return@LaunchedEffect
|
||||
val selected = lens ?: return@LaunchedEffect
|
||||
camera = null; ready.unbindAll(); torch = false
|
||||
if (mode == CaptureMode.VIDEO && !hasAudio) return@LaunchedEffect
|
||||
try {
|
||||
val useCase: UseCase = if (mode == CaptureMode.PHOTO) imageCapture else videoCapture
|
||||
camera = ready.bindToLifecycle(lifecycle, selected.selector(), preview, useCase)
|
||||
error = false
|
||||
LogManager.addLog("INFO", "Capture", "Camera bound mode=$mode lens=${selected.cameraId} " +
|
||||
"photo=${resolution?.label} video=${quality.label}")
|
||||
} catch (e: Exception) {
|
||||
error = true; LogManager.addLog("ERROR", "Capture", "Camera bind failed mode=$mode lens=${selected.cameraId}: ${e.message}")
|
||||
}
|
||||
}
|
||||
LaunchedEffect(phase, output) {
|
||||
val file = output
|
||||
if (phase == CapturePhase.CAPTURED && mode == CaptureMode.PHOTO && file != null) {
|
||||
try {
|
||||
val result = withContext(Dispatchers.IO) {
|
||||
PhotoUtil.metadata(file.path) to PhotoUtil.decodeFitted(file.path, 2048)
|
||||
}
|
||||
photoSize = result.first.width to result.first.height; bitmap = result.second
|
||||
if (bitmap == null) { error = true; LogManager.addLog("ERROR", "Capture", "Photo preview decode failed path=${file.path}") }
|
||||
} catch (e: kotlinx.coroutines.CancellationException) { throw e }
|
||||
catch (e: Exception) { error = true; LogManager.addLog("ERROR", "Capture", "Photo metadata failed: ${e.message}") }
|
||||
}
|
||||
}
|
||||
|
||||
fun capturePhoto() {
|
||||
if (phase != CapturePhase.IDLE || camera == null) return
|
||||
val file = File.createTempFile("photo_msg_", ".jpg", context.cacheDir)
|
||||
output = file; phase = CapturePhase.CAPTURING; error = false
|
||||
imageCapture.targetRotation = context.display?.rotation ?: android.view.Surface.ROTATION_0
|
||||
try {
|
||||
imageCapture.takePicture(ImageCapture.OutputFileOptions.Builder(file).build(), main, object : ImageCapture.OnImageSavedCallback {
|
||||
override fun onImageSaved(results: ImageCapture.OutputFileResults) {
|
||||
if (closed || output != file) { deleteCache(file); return }
|
||||
phase = CapturePhase.CAPTURED
|
||||
LogManager.addLog("INFO", "Capture", "Photo captured path=${file.path} bytes=${file.length()}")
|
||||
}
|
||||
override fun onError(exception: ImageCaptureException) {
|
||||
deleteCache(file)
|
||||
if (closed || output != file) return
|
||||
output = null; phase = CapturePhase.IDLE; error = true
|
||||
LogManager.addLog("ERROR", "Capture", "Photo capture failed code=${exception.imageCaptureError}: ${exception.message}")
|
||||
}
|
||||
})
|
||||
} catch (e: Exception) {
|
||||
deleteCache(file); output = null; phase = CapturePhase.IDLE; error = true
|
||||
LogManager.addLog("ERROR", "Capture", "Photo capture failed: ${e.message}")
|
||||
}
|
||||
}
|
||||
fun startVideo() {
|
||||
if (phase != CapturePhase.IDLE || camera == null || !hasAudio) return
|
||||
val file = File.createTempFile("video_msg_", ".mp4", context.cacheDir)
|
||||
output = file; phase = CapturePhase.CAPTURING; elapsed = 0; error = false
|
||||
videoCapture.targetRotation = context.display?.rotation ?: android.view.Surface.ROTATION_0
|
||||
try {
|
||||
recording = videoCapture.output.prepareRecording(context, FileOutputOptions.Builder(file).build())
|
||||
.withAudioEnabled().start(main) { event ->
|
||||
if (closed || output != file) {
|
||||
if (event is VideoRecordEvent.Finalize) deleteCache(file)
|
||||
} else when (event) {
|
||||
is VideoRecordEvent.Start -> phase = CapturePhase.RECORDING
|
||||
is VideoRecordEvent.Status -> {
|
||||
elapsed = event.recordingStats.recordedDurationNanos / 1_000_000
|
||||
if (elapsed >= 60_000 && phase == CapturePhase.RECORDING) {
|
||||
phase = CapturePhase.FINALIZING; recording?.stop()
|
||||
LogManager.addLog("INFO", "Capture", "Video auto-stop duration=$elapsed")
|
||||
}
|
||||
}
|
||||
is VideoRecordEvent.Finalize -> {
|
||||
recording = null
|
||||
if (event.hasError()) {
|
||||
deleteCache(file); output = null; pendingSend = false; phase = CapturePhase.IDLE; error = true
|
||||
LogManager.addLog("ERROR", "Capture", "Video finalize failed code=${event.error}: ${event.cause?.message}")
|
||||
} else {
|
||||
phase = CapturePhase.CAPTURED
|
||||
LogManager.addLog("INFO", "Capture", "Video finalized path=${file.path} bytes=${file.length()} duration=$elapsed")
|
||||
if (pendingSend) { pendingSend = false; sendResult() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
deleteCache(file); output = null; phase = CapturePhase.IDLE; error = true
|
||||
LogManager.addLog("ERROR", "Capture", "Video start failed: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
val idle = phase == CapturePhase.IDLE
|
||||
Scaffold(topBar = {
|
||||
TopAppBar(title = { Text(stringResource(R.string.camera)) }, navigationIcon = {
|
||||
IconButton(onClick = { reset(); onClose() }) { Icon(Icons.Default.Close, stringResource(R.string.close)) }
|
||||
}, actions = {
|
||||
if (camera?.cameraInfo?.hasFlashUnit() == true) IconButton(enabled = idle || phase == CapturePhase.RECORDING,
|
||||
onClick = {
|
||||
val next = !torch
|
||||
camera?.cameraControl?.enableTorch(next)?.addListener({
|
||||
try { torch = next } catch (e: Exception) { LogManager.addLog("ERROR", "Capture", "Torch failed: ${e.message}") }
|
||||
}, main)
|
||||
}) { Icon(if (torch) Icons.Default.FlashOn else Icons.Default.FlashOff, stringResource(R.string.camera_light)) }
|
||||
})
|
||||
}) { padding ->
|
||||
Box(Modifier.fillMaxSize().background(Color.Black).padding(padding)) {
|
||||
if (phase == CapturePhase.CAPTURED && mode == CaptureMode.PHOTO) {
|
||||
bitmap?.let { ZoomableImage(it, Modifier.fillMaxSize().padding(bottom = 140.dp)) }
|
||||
} else AndroidView(factory = { ctx -> PreviewView(ctx).also {
|
||||
it.scaleType = PreviewView.ScaleType.FIT_CENTER; preview.surfaceProvider = it.surfaceProvider
|
||||
} }, modifier = Modifier.fillMaxSize())
|
||||
Column(Modifier.align(Alignment.TopCenter).fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
CaptureMode.values().forEach { item ->
|
||||
FilterChip(selected = mode == item, enabled = idle, onClick = { mode = item; error = false },
|
||||
label = { Text(stringResource(if (item == CaptureMode.PHOTO) R.string.photo else R.string.capture_video)) })
|
||||
}
|
||||
}
|
||||
if (idle) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
lenses.forEach { item -> FilterChip(selected = lens == item, onClick = { lens = item }, label = { Text(item.label) }) }
|
||||
}
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (mode == CaptureMode.PHOTO) resolutions.forEach { item ->
|
||||
FilterChip(selected = resolution == item, onClick = { resolution = item }, label = { Text(item.label) })
|
||||
} else CaptureQuality.values().forEach { item ->
|
||||
FilterChip(selected = quality == item, onClick = { quality = item }, label = { Text(item.label) })
|
||||
}
|
||||
}
|
||||
}
|
||||
if (error) Text(stringResource(R.string.capture_failed), color = Color.White, modifier = Modifier.padding(8.dp))
|
||||
if (!hasCamera || (mode == CaptureMode.VIDEO && !hasAudio)) Button(onClick = {
|
||||
if (!hasCamera) cameraPermission.launch(Manifest.permission.CAMERA) else audioPermission.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}) { Text(stringResource(if (!hasCamera) R.string.camera_permission_required else R.string.camera_microphone_permission)) }
|
||||
}
|
||||
Column(Modifier.align(Alignment.BottomCenter).navigationBarsPadding().padding(16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
if (mode == CaptureMode.VIDEO) Text("${elapsed / 60_000}:${(elapsed / 1000 % 60).toString().padStart(2, '0')}", color = Color.White)
|
||||
else if (photoSize.first > 0) Text("${photoSize.first}×${photoSize.second}", color = Color.White)
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(24.dp)) {
|
||||
IconButton(onClick = { if (idle) onClose() else reset() }, enabled = phase != CapturePhase.SENDING) {
|
||||
Icon(Icons.Default.Delete, stringResource(R.string.retake), tint = Color.White)
|
||||
}
|
||||
FilledIconButton(modifier = Modifier.size(76.dp), shape = CircleShape,
|
||||
enabled = camera != null && (idle || phase == CapturePhase.RECORDING || phase == CapturePhase.PAUSED),
|
||||
onClick = {
|
||||
when (phase) {
|
||||
CapturePhase.IDLE -> if (mode == CaptureMode.PHOTO) capturePhoto() else startVideo()
|
||||
CapturePhase.RECORDING -> { recording?.pause(); phase = CapturePhase.PAUSED }
|
||||
CapturePhase.PAUSED -> { recording?.resume(); phase = CapturePhase.RECORDING }
|
||||
else -> Unit
|
||||
}
|
||||
}) {
|
||||
Icon(if (mode == CaptureMode.PHOTO) Icons.Default.PhotoCamera else if (phase == CapturePhase.RECORDING)
|
||||
Icons.Default.Pause else Icons.Default.Videocam, stringResource(if (mode == CaptureMode.PHOTO)
|
||||
R.string.take_photo else R.string.record_video), modifier = Modifier.size(36.dp))
|
||||
}
|
||||
IconButton(enabled = phase == CapturePhase.CAPTURED || phase == CapturePhase.RECORDING || phase == CapturePhase.PAUSED,
|
||||
onClick = {
|
||||
if (phase == CapturePhase.CAPTURED) sendResult()
|
||||
else { pendingSend = true; phase = CapturePhase.FINALIZING; recording?.stop() }
|
||||
}) { Icon(Icons.AutoMirrored.Filled.Send, stringResource(R.string.send), tint = Color.White) }
|
||||
}
|
||||
if (phase == CapturePhase.CAPTURING || phase == CapturePhase.FINALIZING) CircularProgressIndicator(Modifier.size(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-350
@@ -1,350 +0,0 @@
|
||||
package com.utun.chat.ui.screens
|
||||
|
||||
import com.utun.chat.R
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Size
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.camera.core.Camera
|
||||
import androidx.camera.core.CameraSelector
|
||||
import androidx.camera.core.ImageCapture
|
||||
import androidx.camera.core.ImageCaptureException
|
||||
import androidx.camera.core.Preview
|
||||
import androidx.camera.core.resolutionselector.ResolutionSelector
|
||||
import androidx.camera.core.resolutionselector.ResolutionStrategy
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
import androidx.camera.view.PreviewView
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.FlashOff
|
||||
import androidx.compose.material.icons.filled.FlashOn
|
||||
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.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.utun.chat.data.CameraLensManager
|
||||
import com.utun.chat.data.LensType
|
||||
import com.utun.chat.data.LensOption
|
||||
import com.utun.chat.data.LogManager
|
||||
import com.utun.chat.data.PhotoResolution
|
||||
import com.utun.chat.data.PhotoUtil
|
||||
import com.utun.chat.ui.components.ZoomableImage
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
private enum class PhotoPhase { IDLE, CAPTURING, CAPTURED }
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PhotoRecordScreen(
|
||||
onSend: (String, Int, Int) -> Unit,
|
||||
onClose: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
val cameraExecutor = remember { Executors.newSingleThreadExecutor() }
|
||||
|
||||
var hasCamera by remember {
|
||||
mutableStateOf(
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
|
||||
)
|
||||
}
|
||||
val camLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { hasCamera = it }
|
||||
|
||||
LaunchedEffect(Unit) { if (!hasCamera) camLauncher.launch(Manifest.permission.CAMERA) }
|
||||
|
||||
val providerRef = remember { mutableStateOf<ProcessCameraProvider?>(null) }
|
||||
var lenses by remember { mutableStateOf<List<LensOption>>(emptyList()) }
|
||||
var selectedLens by remember { mutableStateOf<LensOption?>(null) }
|
||||
var resolutions by remember { mutableStateOf<List<PhotoResolution>>(emptyList()) }
|
||||
var selectedResolution by remember { mutableStateOf<PhotoResolution?>(null) }
|
||||
|
||||
val imageCapture = remember(selectedResolution) {
|
||||
val builder = ImageCapture.Builder()
|
||||
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
|
||||
selectedResolution?.let { r ->
|
||||
val selector = ResolutionSelector.Builder()
|
||||
.setResolutionStrategy(ResolutionStrategy(
|
||||
Size(r.width, r.height),
|
||||
ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER))
|
||||
.build()
|
||||
builder.setResolutionSelector(selector)
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
val preview = remember { Preview.Builder().build() }
|
||||
val currentPreview by rememberUpdatedState(preview)
|
||||
val currentImageCapture by rememberUpdatedState(imageCapture)
|
||||
|
||||
var phase by remember { mutableStateOf(PhotoPhase.IDLE) }
|
||||
var outputFile by remember { mutableStateOf<File?>(null) }
|
||||
var photoWidth by remember { mutableStateOf(0) }
|
||||
var photoHeight by remember { mutableStateOf(0) }
|
||||
var previewBitmap by remember { mutableStateOf<Bitmap?>(null) }
|
||||
var boundCamera by remember { mutableStateOf<Camera?>(null) }
|
||||
var torchOn by remember { mutableStateOf(false) }
|
||||
|
||||
fun bindCamera(selector: CameraSelector) {
|
||||
val provider = providerRef.value ?: return
|
||||
try {
|
||||
provider.unbindAll()
|
||||
boundCamera = provider.bindToLifecycle(lifecycleOwner, selector, currentPreview, currentImageCapture)
|
||||
torchOn = false
|
||||
LogManager.addLog("INFO", "PhotoRecord", "camera bound")
|
||||
} catch (e: Exception) {
|
||||
LogManager.addLog("ERROR", "PhotoRecord", "bind failed: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
fun selectLens(lens: LensOption) {
|
||||
selectedLens = lens
|
||||
val provider = providerRef.value
|
||||
val list = if (provider != null) CameraLensManager.photoResolutions(provider, lens.cameraId) else emptyList()
|
||||
resolutions = list
|
||||
selectedResolution = list.lastOrNull()
|
||||
bindCamera(lens.selector())
|
||||
}
|
||||
|
||||
fun readDimensions(file: File): Pair<Int, Int> = PhotoUtil.orientedDimensions(file.absolutePath)
|
||||
|
||||
fun capture() {
|
||||
if (phase != PhotoPhase.IDLE) return
|
||||
val file = File(context.cacheDir, "photo_msg_${System.currentTimeMillis()}.jpg")
|
||||
outputFile = file
|
||||
phase = PhotoPhase.CAPTURING
|
||||
try {
|
||||
val options = ImageCapture.OutputFileOptions.Builder(file).build()
|
||||
imageCapture.takePicture(options, cameraExecutor, object : ImageCapture.OnImageSavedCallback {
|
||||
override fun onImageSaved(results: ImageCapture.OutputFileResults) {
|
||||
val dims = readDimensions(file)
|
||||
photoWidth = dims.first
|
||||
photoHeight = dims.second
|
||||
LogManager.addLog("INFO", "PhotoRecord", "captured: ${file.absolutePath} (${file.length()} bytes) ${dims.first}x${dims.second}")
|
||||
phase = PhotoPhase.CAPTURED
|
||||
}
|
||||
override fun onError(exception: ImageCaptureException) {
|
||||
LogManager.addLog("ERROR", "PhotoRecord", "capture error: ${exception.message}")
|
||||
file.delete()
|
||||
outputFile = null
|
||||
phase = PhotoPhase.IDLE
|
||||
}
|
||||
})
|
||||
} catch (e: Exception) {
|
||||
LogManager.addLog("ERROR", "PhotoRecord", "capture failed: ${e.message}")
|
||||
phase = PhotoPhase.IDLE
|
||||
}
|
||||
}
|
||||
|
||||
fun discardAndReset() {
|
||||
outputFile?.delete()
|
||||
outputFile = null
|
||||
previewBitmap = null
|
||||
photoWidth = 0
|
||||
photoHeight = 0
|
||||
phase = PhotoPhase.IDLE
|
||||
LogManager.addLog("INFO", "PhotoRecord", "discarded")
|
||||
}
|
||||
|
||||
/* load downsampled preview when captured */
|
||||
LaunchedEffect(phase) {
|
||||
if (phase == PhotoPhase.CAPTURED) {
|
||||
val file = outputFile ?: return@LaunchedEffect
|
||||
previewBitmap = withContext(Dispatchers.IO) { PhotoUtil.decodeOriented(file.absolutePath, 4) }
|
||||
}
|
||||
}
|
||||
|
||||
/* rebind camera after resolution change (imageCapture is rebuilt) */
|
||||
LaunchedEffect(selectedResolution) {
|
||||
if (providerRef.value != null) {
|
||||
selectedLens?.let { bindCamera(it.selector()) }
|
||||
LogManager.addLog("INFO", "PhotoRecord", "resolution switched to ${selectedResolution?.label ?: "full"}")
|
||||
}
|
||||
}
|
||||
|
||||
/* init provider + enumerate lenses + bind front */
|
||||
DisposableEffect(hasCamera) {
|
||||
if (hasCamera) {
|
||||
val future = ProcessCameraProvider.getInstance(context)
|
||||
future.addListener({
|
||||
try {
|
||||
val provider = future.get()
|
||||
providerRef.value = provider
|
||||
val list = CameraLensManager.enumerate(provider)
|
||||
lenses = list
|
||||
val default = list.firstOrNull { it.type == LensType.SELFIE } ?: list.firstOrNull()
|
||||
if (default != null) {
|
||||
selectLens(default)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
LogManager.addLog("ERROR", "PhotoRecord", "provider init failed: ${e.message}")
|
||||
}
|
||||
}, ContextCompat.getMainExecutor(context))
|
||||
}
|
||||
onDispose {
|
||||
providerRef.value?.unbindAll()
|
||||
providerRef.value = null
|
||||
cameraExecutor.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.photo)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = { discardAndReset(); onClose() }) { Icon(Icons.Filled.Close, stringResource(R.string.close)) }
|
||||
},
|
||||
actions = {
|
||||
if (boundCamera?.cameraInfo?.hasFlashUnit() == true) {
|
||||
IconButton(onClick = {
|
||||
val next = !torchOn
|
||||
try { boundCamera?.cameraControl?.enableTorch(next) } catch (_: Exception) {}
|
||||
torchOn = next
|
||||
}) {
|
||||
Icon(if (torchOn) Icons.Filled.FlashOn else Icons.Filled.FlashOff, stringResource(R.string.camera_light), tint = if (torchOn) Color(0xFFFFD600) else Color.White)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Box(Modifier.fillMaxSize().background(Color.Black).padding(padding)) {
|
||||
if (!hasCamera) {
|
||||
Column(Modifier.align(Alignment.Center), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text(stringResource(R.string.camera_permission_required), color = Color.White, fontSize = 16.sp)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Button(onClick = { camLauncher.launch(Manifest.permission.CAMERA) }) { Text(stringResource(R.string.camera)) }
|
||||
}
|
||||
} else if (phase == PhotoPhase.CAPTURED) {
|
||||
Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
previewBitmap?.let { ZoomableImage(it, Modifier.fillMaxSize()) }
|
||||
}
|
||||
Text(
|
||||
"${photoWidth}×${photoHeight}",
|
||||
color = Color.White.copy(alpha = 0.7f), fontSize = 13.sp
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
} else {
|
||||
AndroidView(
|
||||
factory = { ctx ->
|
||||
PreviewView(ctx).also { pv ->
|
||||
pv.scaleType = PreviewView.ScaleType.FIT_CENTER
|
||||
preview.surfaceProvider = pv.surfaceProvider
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxSize()
|
||||
)
|
||||
|
||||
/* lens chips */
|
||||
if (phase == PhotoPhase.IDLE) {
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.TopCenter).padding(top = 8.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
lenses.forEach { lens ->
|
||||
val selected = selectedLens?.cameraId == lens.cameraId
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = if (selected) Color(0xFF214563) else Color(0xFF24323D),
|
||||
modifier = Modifier.clickable { selectLens(lens) }
|
||||
) {
|
||||
Text(
|
||||
lens.label,
|
||||
color = Color(0xFFE6EDF3),
|
||||
fontSize = 13.sp,
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
resolutions.forEach { r ->
|
||||
val selected = r == selectedResolution
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = if (selected) Color(0xFF214563) else Color(0xFF24323D),
|
||||
modifier = Modifier.clickable { selectedResolution = r }
|
||||
) {
|
||||
Text(
|
||||
r.label,
|
||||
color = Color(0xFFE6EDF3),
|
||||
fontSize = 13.sp,
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* bottom controls */
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
|
||||
.navigationBarsPadding().padding(16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (phase == PhotoPhase.CAPTURED) {
|
||||
Box(
|
||||
modifier = Modifier.size(52.dp)
|
||||
.background(Color(0xCC000000), CircleShape)
|
||||
.clickable { discardAndReset() },
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Icon(Icons.Filled.Delete, stringResource(R.string.retake), tint = Color.White, modifier = Modifier.size(26.dp))
|
||||
}
|
||||
Spacer(Modifier.width(28.dp))
|
||||
Box(
|
||||
modifier = Modifier.size(52.dp)
|
||||
.background(Color(0xFF24633D), CircleShape)
|
||||
.clickable {
|
||||
outputFile?.let { f -> if (f.length() > 0) onSend(f.absolutePath, photoWidth, photoHeight) else onClose() }
|
||||
},
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Icon(Icons.AutoMirrored.Filled.Send, stringResource(R.string.send), tint = Color.White, modifier = Modifier.size(26.dp))
|
||||
}
|
||||
} else {
|
||||
/* shutter */
|
||||
Box(
|
||||
modifier = Modifier.size(76.dp)
|
||||
.background(Color.White.copy(alpha = 0.9f), CircleShape)
|
||||
.clickable(enabled = phase == PhotoPhase.IDLE) { capture() },
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Box(
|
||||
Modifier.size(60.dp)
|
||||
.background(if (phase == PhotoPhase.CAPTURING) Color(0x88FFFFFF) else Color.White, CircleShape)
|
||||
.padding(4.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-418
@@ -1,418 +0,0 @@
|
||||
package com.utun.chat.ui.screens
|
||||
|
||||
import com.utun.chat.R
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.camera.core.Camera
|
||||
import androidx.camera.core.CameraSelector
|
||||
import androidx.camera.core.Preview
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
import androidx.camera.video.FileOutputOptions
|
||||
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.PreviewView
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.FlashOff
|
||||
import androidx.compose.material.icons.filled.FlashOn
|
||||
import androidx.compose.material.icons.filled.Pause
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
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.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.utun.chat.data.CameraLensManager
|
||||
import com.utun.chat.data.LensType
|
||||
import com.utun.chat.data.LensOption
|
||||
import com.utun.chat.data.LogManager
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import java.io.File
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
private const val MAX_VIDEO_MS = 60_000
|
||||
|
||||
private enum class Phase { IDLE, RECORDING, PAUSED, STOPPED }
|
||||
|
||||
private enum class VideoQuality(val label: String, val quality: Quality, val bitrate: Int) {
|
||||
P480_512K("480p 512k", Quality.SD, 512_000),
|
||||
P480_1M("480p 1M", Quality.SD, 1_000_000),
|
||||
P720_2M("720p 2M", Quality.HD, 2_000_000),
|
||||
P1080_45M("1080p 4.5M", Quality.FHD, 4_500_000);
|
||||
|
||||
companion object { val DEFAULT = P720_2M }
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun VideoRecordScreen(
|
||||
onSend: (String) -> Unit,
|
||||
onClose: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
val cameraExecutor = remember { Executors.newSingleThreadExecutor() }
|
||||
|
||||
var hasCamera by remember {
|
||||
mutableStateOf(
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
|
||||
)
|
||||
}
|
||||
var hasAudio by remember {
|
||||
mutableStateOf(
|
||||
ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
)
|
||||
}
|
||||
val camLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { hasCamera = it }
|
||||
val audLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { hasAudio = it }
|
||||
|
||||
LaunchedEffect(Unit) { if (!hasCamera) camLauncher.launch(Manifest.permission.CAMERA) }
|
||||
LaunchedEffect(hasCamera) { if (hasCamera && !hasAudio) audLauncher.launch(Manifest.permission.RECORD_AUDIO) }
|
||||
|
||||
val providerRef = remember { mutableStateOf<ProcessCameraProvider?>(null) }
|
||||
var lenses by remember { mutableStateOf<List<LensOption>>(emptyList()) }
|
||||
var selectedLens by remember { mutableStateOf<LensOption?>(null) }
|
||||
var quality by remember { mutableStateOf(VideoQuality.DEFAULT) }
|
||||
|
||||
val recorder = remember(quality) {
|
||||
Recorder.Builder()
|
||||
.setQualitySelector(QualitySelector.from(quality.quality))
|
||||
.setTargetVideoEncodingBitRate(quality.bitrate)
|
||||
.build()
|
||||
}
|
||||
val videoCapture = remember(quality) { VideoCapture.withOutput(recorder) }
|
||||
val preview = remember { Preview.Builder().build() }
|
||||
val currentPreview by rememberUpdatedState(preview)
|
||||
val currentVideoCapture by rememberUpdatedState(videoCapture)
|
||||
|
||||
var phase by remember { mutableStateOf(Phase.IDLE) }
|
||||
var recording by remember { mutableStateOf<Recording?>(null) }
|
||||
var outputFile by remember { mutableStateOf<File?>(null) }
|
||||
var elapsedMs by remember { mutableStateOf(0) }
|
||||
var pendingSend by remember { mutableStateOf(false) }
|
||||
var sendRequested by remember { mutableStateOf(false) }
|
||||
var boundCamera by remember { mutableStateOf<Camera?>(null) }
|
||||
var torchOn by remember { mutableStateOf(false) }
|
||||
|
||||
fun bindCamera(selector: CameraSelector) {
|
||||
val provider = providerRef.value ?: return
|
||||
try {
|
||||
provider.unbindAll()
|
||||
boundCamera = provider.bindToLifecycle(lifecycleOwner, selector, currentPreview, currentVideoCapture)
|
||||
torchOn = false
|
||||
LogManager.addLog("INFO", "VideoRecord", "camera bound")
|
||||
} catch (e: Exception) {
|
||||
LogManager.addLog("ERROR", "VideoRecord", "bind failed: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
fun startRecording() {
|
||||
val file = File(context.cacheDir, "video_msg_${System.currentTimeMillis()}.mp4")
|
||||
outputFile = file
|
||||
elapsedMs = 0
|
||||
try {
|
||||
val pending = recorder.prepareRecording(context, FileOutputOptions.Builder(file).build())
|
||||
.withAudioEnabled()
|
||||
recording = pending.start(ContextCompat.getMainExecutor(context)) { event ->
|
||||
when (event) {
|
||||
is VideoRecordEvent.Start -> { phase = Phase.RECORDING }
|
||||
is VideoRecordEvent.Finalize -> {
|
||||
recording = null
|
||||
if (event.hasError()) {
|
||||
LogManager.addLog("ERROR", "VideoRecord", "finalize error: ${event.error}")
|
||||
file.delete()
|
||||
phase = Phase.IDLE
|
||||
} else {
|
||||
LogManager.addLog("INFO", "VideoRecord", "finalized: ${file.absolutePath} (${file.length()} bytes)")
|
||||
phase = Phase.STOPPED
|
||||
if (pendingSend) { pendingSend = false; sendRequested = true }
|
||||
}
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
LogManager.addLog("INFO", "VideoRecord", "recording started -> ${file.absolutePath}")
|
||||
} catch (e: Exception) {
|
||||
LogManager.addLog("ERROR", "VideoRecord", "start failed: ${e.message}")
|
||||
phase = Phase.IDLE
|
||||
}
|
||||
}
|
||||
|
||||
fun discardAndReset() {
|
||||
recording?.let {
|
||||
try { it.close() } catch (_: Exception) {}
|
||||
}
|
||||
recording = null
|
||||
outputFile?.delete()
|
||||
outputFile = null
|
||||
elapsedMs = 0
|
||||
pendingSend = false
|
||||
phase = Phase.IDLE
|
||||
LogManager.addLog("INFO", "VideoRecord", "discarded")
|
||||
}
|
||||
|
||||
/* timer + 60s auto-stop */
|
||||
LaunchedEffect(phase) {
|
||||
while (phase == Phase.RECORDING && isActive) {
|
||||
delay(100)
|
||||
elapsedMs += 100
|
||||
if (elapsedMs >= MAX_VIDEO_MS) {
|
||||
LogManager.addLog("INFO", "VideoRecord", "auto-stop at ${MAX_VIDEO_MS}ms")
|
||||
recording?.stop()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* send after finalize */
|
||||
LaunchedEffect(sendRequested) {
|
||||
if (sendRequested) {
|
||||
sendRequested = false
|
||||
val file = outputFile
|
||||
if (file != null && file.length() > 0) onSend(file.absolutePath) else onClose()
|
||||
}
|
||||
}
|
||||
|
||||
/* rebind camera after quality change (recorder/videoCapture are rebuilt) */
|
||||
LaunchedEffect(quality) {
|
||||
if (providerRef.value != null) {
|
||||
selectedLens?.let { bindCamera(it.selector()) }
|
||||
LogManager.addLog("INFO", "VideoRecord", "quality switched to ${quality.label} ${quality.bitrate / 1000}k")
|
||||
}
|
||||
}
|
||||
|
||||
/* init provider + enumerate lenses + bind front */
|
||||
DisposableEffect(hasCamera && hasAudio) {
|
||||
if (hasCamera && hasAudio) {
|
||||
val future = ProcessCameraProvider.getInstance(context)
|
||||
future.addListener({
|
||||
try {
|
||||
val provider = future.get()
|
||||
providerRef.value = provider
|
||||
val list = CameraLensManager.enumerate(provider)
|
||||
lenses = list
|
||||
val default = list.firstOrNull { it.type == LensType.SELFIE } ?: list.firstOrNull()
|
||||
if (default != null) {
|
||||
selectedLens = default
|
||||
bindCamera(default.selector())
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
LogManager.addLog("ERROR", "VideoRecord", "provider init failed: ${e.message}")
|
||||
}
|
||||
}, ContextCompat.getMainExecutor(context))
|
||||
}
|
||||
onDispose {
|
||||
providerRef.value?.unbindAll()
|
||||
providerRef.value = null
|
||||
cameraExecutor.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.video_message)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = { discardAndReset(); onClose() }) { Icon(Icons.Filled.Close, stringResource(R.string.close)) }
|
||||
},
|
||||
actions = {
|
||||
if (boundCamera?.cameraInfo?.hasFlashUnit() == true) {
|
||||
IconButton(onClick = {
|
||||
val next = !torchOn
|
||||
try { boundCamera?.cameraControl?.enableTorch(next) } catch (_: Exception) {}
|
||||
torchOn = next
|
||||
}) {
|
||||
Icon(if (torchOn) Icons.Filled.FlashOn else Icons.Filled.FlashOff, stringResource(R.string.camera_light), tint = if (torchOn) Color(0xFFFFD600) else Color.White)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Box(Modifier.fillMaxSize().background(Color.Black).padding(padding)) {
|
||||
if (!hasCamera || !hasAudio) {
|
||||
Column(Modifier.align(Alignment.Center), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text(stringResource(R.string.camera_microphone_permission), color = Color.White, fontSize = 16.sp)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Row {
|
||||
if (!hasCamera) Button(onClick = { camLauncher.launch(Manifest.permission.CAMERA) }) { Text(stringResource(R.string.camera)) }
|
||||
if (hasCamera && !hasAudio) Button(onClick = { audLauncher.launch(Manifest.permission.RECORD_AUDIO) }) { Text(stringResource(R.string.microphone)) }
|
||||
}
|
||||
}
|
||||
} else {
|
||||
AndroidView(
|
||||
factory = { ctx ->
|
||||
PreviewView(ctx).also { pv ->
|
||||
pv.scaleType = PreviewView.ScaleType.FIT_CENTER
|
||||
preview.surfaceProvider = pv.surfaceProvider
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxSize()
|
||||
)
|
||||
|
||||
/* lens + quality chips */
|
||||
if (phase == Phase.IDLE) {
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.TopCenter).padding(top = 8.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
lenses.forEach { lens ->
|
||||
val selected = selectedLens?.cameraId == lens.cameraId
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = if (selected) Color(0xFF214563) else Color(0xFF24323D),
|
||||
modifier = Modifier.clickable {
|
||||
selectedLens = lens
|
||||
bindCamera(lens.selector())
|
||||
}
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
) {
|
||||
Text(
|
||||
lens.label,
|
||||
color = Color(0xFFE6EDF3),
|
||||
fontSize = 13.sp
|
||||
)
|
||||
if (lens.mm.isNotEmpty()) {
|
||||
Text(
|
||||
lens.mm,
|
||||
color = Color(0xFFAEBCC8),
|
||||
fontSize = 11.sp
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
VideoQuality.values().forEach { q ->
|
||||
val selected = q == quality
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = if (selected) Color(0xFF214563) else Color(0xFF24323D),
|
||||
modifier = Modifier.clickable { quality = q }
|
||||
) {
|
||||
Text(
|
||||
q.label,
|
||||
color = Color(0xFFE6EDF3),
|
||||
fontSize = 13.sp,
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* bottom controls */
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
|
||||
.navigationBarsPadding().padding(16.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Text(
|
||||
when (phase) {
|
||||
Phase.RECORDING -> "\uD83D\uDD34 ${formatDuration(elapsedMs)}"
|
||||
Phase.PAUSED -> "\u23F8 ${formatDuration(elapsedMs)}"
|
||||
Phase.STOPPED -> "\u2705 ${formatDuration(elapsedMs)}"
|
||||
Phase.IDLE -> "0:00"
|
||||
},
|
||||
color = Color.White, fontSize = 16.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.Bold
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
/* discard / close */
|
||||
Box(
|
||||
modifier = Modifier.size(52.dp)
|
||||
.background(Color(0xCC000000), CircleShape)
|
||||
.clickable { if (phase == Phase.IDLE) onClose() else discardAndReset() },
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Icon(Icons.Filled.Delete, if (phase == Phase.IDLE) stringResource(R.string.close) else stringResource(R.string.delete), tint = Color.White, modifier = Modifier.size(26.dp))
|
||||
}
|
||||
Spacer(Modifier.width(28.dp))
|
||||
|
||||
/* record/pause/resume */
|
||||
Box(
|
||||
modifier = Modifier.size(76.dp)
|
||||
.background(
|
||||
when (phase) { Phase.RECORDING -> Color(0xFFB32632); else -> Color(0xFFB32632) },
|
||||
CircleShape
|
||||
)
|
||||
.clickable {
|
||||
when (phase) {
|
||||
Phase.IDLE -> startRecording()
|
||||
Phase.RECORDING -> { recording?.pause(); phase = Phase.PAUSED }
|
||||
Phase.PAUSED -> { recording?.resume(); phase = Phase.RECORDING }
|
||||
Phase.STOPPED -> discardAndReset()
|
||||
}
|
||||
},
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
val icon = when (phase) {
|
||||
Phase.RECORDING -> Icons.Filled.Pause
|
||||
Phase.PAUSED -> Icons.Filled.PlayArrow
|
||||
Phase.STOPPED -> Icons.Filled.Close
|
||||
Phase.IDLE -> Icons.Filled.PlayArrow
|
||||
}
|
||||
if (phase == Phase.IDLE || phase == Phase.STOPPED) {
|
||||
Box(Modifier.size(30.dp).background(Color.White, CircleShape))
|
||||
} else {
|
||||
Icon(icon, contentDescription = null, tint = Color.White, modifier = Modifier.size(34.dp))
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(28.dp))
|
||||
|
||||
/* send */
|
||||
val canSend = (phase == Phase.RECORDING || phase == Phase.PAUSED || phase == Phase.STOPPED)
|
||||
Box(
|
||||
modifier = Modifier.size(52.dp)
|
||||
.background(if (canSend) Color(0xFF24633D) else Color(0x33000000), CircleShape)
|
||||
.clickable(enabled = canSend) {
|
||||
if (phase == Phase.STOPPED) {
|
||||
outputFile?.let { onSend(it.absolutePath) }
|
||||
} else {
|
||||
pendingSend = true
|
||||
recording?.stop()
|
||||
}
|
||||
},
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Icon(Icons.AutoMirrored.Filled.Send, stringResource(R.string.send), tint = Color.White, modifier = Modifier.size(26.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatDuration(ms: Int): String {
|
||||
val secs = (ms.coerceAtLeast(0)) / 1000
|
||||
return "%d:%02d".format(secs / 60, secs % 60)
|
||||
}
|
||||
Reference in new issue
Block a user