diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CameraCaptureSettings.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CameraCaptureSettings.kt index 7a83a3f15..47984db8a 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CameraCaptureSettings.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/CameraCaptureSettings.kt @@ -1,7 +1,8 @@ package com.utun.chat.data /** Независимый выбор фото: пустая камера означает обычную заднюю, нулевые размеры — максимальное разрешение. */ -data class PhotoCaptureSettings(val camera: String = "", val width: Int = 0, val height: Int = 0, val jpegQuality: Int = 85) { +data class PhotoCaptureSettings(val camera: String = "", val width: Int = 0, val height: Int = 0, val jpegQuality: Int = 85, + val orientation: StreamOrientation = StreamOrientation.AUTO) { init { require((width == 0 && height == 0) || (width in 1..16384 && height in 1..16384)) require(jpegQuality in QUALITIES) @@ -17,7 +18,8 @@ data class PhotoCaptureSettings(val camera: String = "", val width: Int = 0, val } /** Выбор записи видео хранится отдельно от фото, звонков и трансляций; height — метка 480p/720p/1080p. */ -data class VideoCaptureSettings(val camera: String = "", val height: Int = 720, val codec: Int = 1, val bitrate: Int = 2_000_000) { +data class VideoCaptureSettings(val camera: String = "", val height: Int = 720, val codec: Int = 1, val bitrate: Int = 2_000_000, + val orientation: StreamOrientation = StreamOrientation.AUTO) { init { require(height in HEIGHTS); require(codec in 1..2); require(bitrate in BITRATES) } fun resolveCamera(lenses: List): LensOption? = lenses.firstOrNull { it.cameraId == camera } diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/ConfigProvider.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/ConfigProvider.kt index dc62c734e..804d13be4 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/ConfigProvider.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/ConfigProvider.kt @@ -74,10 +74,12 @@ class ConfigProvider(private val context: Context) { private val photoWidth = intPreferencesKey("photo_capture_width") private val photoHeight = intPreferencesKey("photo_capture_height") private val photoJpegQuality = intPreferencesKey("photo_capture_jpeg_quality") + private val photoRotation = intPreferencesKey("photo_capture_rotation") private val videoCamera = stringPreferencesKey("video_capture_camera") private val videoHeight = intPreferencesKey("video_capture_height") private val videoCodec = intPreferencesKey("video_capture_codec") private val videoBitrate = intPreferencesKey("video_capture_bitrate") + private val videoRotation = intPreferencesKey("video_capture_rotation") private val callVideoCamera = stringPreferencesKey("call_video_camera") private val callVideoWidth = intPreferencesKey("call_video_width") private val callVideoHeight = intPreferencesKey("call_video_height") @@ -226,10 +228,12 @@ class ConfigProvider(private val context: Context) { /** Очередь Application сохраняет выбор после закрытия экрана и завершает записи перед последующим чтением. */ suspend fun getPhotoCaptureSettings(): PhotoCaptureSettings = configFiles.submit("load photo capture") { val prefs = context.dataStore.data.first() - try { PhotoCaptureSettings(prefs[photoCamera] ?: "", prefs[photoWidth] ?: 0, prefs[photoHeight] ?: 0, prefs[photoJpegQuality] ?: 85) } + try { PhotoCaptureSettings(prefs[photoCamera] ?: "", prefs[photoWidth] ?: 0, prefs[photoHeight] ?: 0, prefs[photoJpegQuality] ?: 85, + requireNotNull(StreamOrientation.entries.firstOrNull { it.degrees == (prefs[photoRotation] ?: StreamOrientation.AUTO.degrees) })) } catch (e: IllegalArgumentException) { LogManager.addLog("WARN", "Capture", "Invalid photo settings camera=${prefs[photoCamera]} " + - "size=${prefs[photoWidth]}x${prefs[photoHeight]} jpegQuality=${prefs[photoJpegQuality]}; using defaults") + "size=${prefs[photoWidth]}x${prefs[photoHeight]} jpegQuality=${prefs[photoJpegQuality]} " + + "rotation=${prefs[photoRotation]}; using defaults") PhotoCaptureSettings() } }.await() @@ -238,16 +242,19 @@ class ConfigProvider(private val context: Context) { context.dataStore.edit { prefs -> prefs[photoCamera] = settings.camera; prefs[photoWidth] = settings.width; prefs[photoHeight] = settings.height prefs[photoJpegQuality] = settings.jpegQuality + prefs[photoRotation] = settings.orientation.degrees } LogManager.addLog("INFO", "Capture", "Photo settings saved: $settings") } suspend fun getVideoCaptureSettings(): VideoCaptureSettings = configFiles.submit("load video capture") { val prefs = context.dataStore.data.first() - try { VideoCaptureSettings(prefs[videoCamera] ?: "", prefs[videoHeight] ?: 720, prefs[videoCodec] ?: 1, prefs[videoBitrate] ?: 2_000_000) } + try { VideoCaptureSettings(prefs[videoCamera] ?: "", prefs[videoHeight] ?: 720, prefs[videoCodec] ?: 1, prefs[videoBitrate] ?: 2_000_000, + requireNotNull(StreamOrientation.entries.firstOrNull { it.degrees == (prefs[videoRotation] ?: StreamOrientation.AUTO.degrees) })) } catch (e: IllegalArgumentException) { LogManager.addLog("WARN", "Capture", "Invalid video settings camera=${prefs[videoCamera]} " + - "height=${prefs[videoHeight]} codec=${prefs[videoCodec]} bitrate=${prefs[videoBitrate]}; using defaults") + "height=${prefs[videoHeight]} codec=${prefs[videoCodec]} bitrate=${prefs[videoBitrate]} " + + "rotation=${prefs[videoRotation]}; using defaults") VideoCaptureSettings() } }.await() @@ -256,6 +263,7 @@ class ConfigProvider(private val context: Context) { context.dataStore.edit { prefs -> prefs[videoCamera] = settings.camera; prefs[videoHeight] = settings.height prefs[videoCodec] = settings.codec; prefs[videoBitrate] = settings.bitrate + prefs[videoRotation] = settings.orientation.degrees } LogManager.addLog("INFO", "Capture", "Video settings saved: $settings") } diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureConfig.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureConfig.kt index 11ebc468e..3089dff0c 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureConfig.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/data/StreamCaptureConfig.kt @@ -5,8 +5,11 @@ enum class StreamOrientation(val degrees: Int) { // -1 хранится только в настройках; в видео передаётся вычисленный угол 0/90/180/270. AUTO(-1), UPRIGHT(0), RIGHT(90), UPSIDE_DOWN(180), LEFT(270); + /** Целевой поворот CameraX/Surface; датчик положения отсчитывает угол в противоположную сторону. */ + fun targetDegrees(deviceDegrees: Int = 0): Int = if (this == AUTO) (360 - deviceDegrees) % 360 else degrees + fun sensorRotation(sensor: Int, front: Boolean, deviceDegrees: Int = 0): Int { - val turn = if (this == AUTO) (360 - deviceDegrees) % 360 else degrees + val turn = targetDegrees(deviceDegrees) return (sensor + (if (front) turn else -turn) + 360) % 360 } } diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/CameraRecordScreen.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/CameraRecordScreen.kt index 44b5728ed..a4d775984 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/CameraRecordScreen.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/CameraRecordScreen.kt @@ -5,8 +5,11 @@ import android.content.pm.PackageManager import android.graphics.Bitmap import android.media.MediaExtractor import android.media.MediaFormat +import android.os.SystemClock import android.text.format.Formatter import android.util.Size +import android.view.OrientationEventListener +import android.view.Surface import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts @@ -34,7 +37,6 @@ import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign @@ -48,6 +50,8 @@ import com.utun.chat.ChatApplication import com.utun.chat.data.* import com.utun.chat.ui.components.ZoomableImage import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File @@ -55,7 +59,7 @@ import kotlin.math.roundToInt enum class CaptureMode { PHOTO, VIDEO } private enum class CapturePhase { IDLE, CAPTURING, RECORDING, PAUSED, FINALIZING, CAPTURED, SENDING } -private enum class CameraOption { CAMERA, CODEC, RESOLUTION, BITRATE, JPEG_QUALITY } +private enum class CameraOption { CAMERA, CODEC, RESOLUTION, ORIENTATION, BITRATE, JPEG_QUALITY } private enum class CaptureResolution(val label: String, val quality: Quality, val height: Int) { SD("480p", Quality.SD, 480), HD("720p", Quality.HD, 720), FHD("1080p", Quality.FHD, 1080) } @@ -65,7 +69,7 @@ private enum class CaptureResolution(val label: String, val quality: Quality, va @Composable fun CameraRecordScreen(initialMode: CaptureMode, onSend: (String, CaptureMode) -> Unit, onClose: () -> Unit) { val context = LocalContext.current - val view = LocalView.current + val displayDegrees = StreamDisplayDegrees() val lifecycle = LocalLifecycleOwner.current val main = remember(context) { ContextCompat.getMainExecutor(context) } val scope = rememberCoroutineScope() @@ -101,6 +105,8 @@ fun CameraRecordScreen(initialMode: CaptureMode, onSend: (String, CaptureMode) - var bitrate by remember { mutableIntStateOf(2_000_000) } var jpegQuality by remember { mutableIntStateOf(85) } var codec by remember { mutableStateOf(StreamVideoCodec.H264) } + var orientation by remember { mutableStateOf(StreamOrientation.AUTO) } + var deviceDegrees by remember { mutableIntStateOf((360 - displayDegrees) % 360) } var videoOptions by remember(provider, lens?.cameraId) { mutableStateOf>?>(null) } @@ -134,11 +140,11 @@ fun CameraRecordScreen(initialMode: CaptureMode, onSend: (String, CaptureMode) - } fun rememberPhotoSettings() { - photoSettings = PhotoCaptureSettings(lens?.cameraId.orEmpty(), resolution?.width ?: 0, resolution?.height ?: 0, jpegQuality) + photoSettings = PhotoCaptureSettings(lens?.cameraId.orEmpty(), resolution?.width ?: 0, resolution?.height ?: 0, jpegQuality, orientation) preferences.savePhotoCaptureSettings(photoSettings) } fun rememberVideoSettings() { - videoSettings = VideoCaptureSettings(lens?.cameraId.orEmpty(), quality.height, codec.id, bitrate) + videoSettings = VideoCaptureSettings(lens?.cameraId.orEmpty(), quality.height, codec.id, bitrate, orientation) preferences.saveVideoCaptureSettings(videoSettings) } @@ -166,6 +172,46 @@ fun CameraRecordScreen(initialMode: CaptureMode, onSend: (String, CaptureMode) - } BackHandler { reset(); onClose() } + // Авто работает независимо от автоповорота экрана; для MP4 угол фиксируется при старте записи. + DisposableEffect(hasCamera, settingsReady, mode, orientation, phase == CapturePhase.IDLE) { + val tracker = CallVideoOrientation() + fun updateOrientation() { + deviceDegrees = tracker.degrees + LogManager.addLog("DEBUG", "Capture", "Device orientation mode=$mode degrees=$deviceDegrees") + } + val listener = object : OrientationEventListener(context) { + override fun onOrientationChanged(angle: Int) { + if (tracker.observe(angle, SystemClock.elapsedRealtime())) updateOrientation() + } + } + val auto = hasCamera && settingsReady && orientation == StreamOrientation.AUTO && phase == CapturePhase.IDLE + if (auto) { + if (listener.canDetectOrientation()) listener.enable() + else LogManager.addLog("WARN", "Capture", "Orientation sensor unavailable mode=$mode; using deviceDegrees=$deviceDegrees") + } + // Подтверждение нужно и без новых событий: датчик может перестать присылать неизменный угол. + val confirmation = if (auto) scope.launch { + while (isActive) { + delay(250) + if (tracker.confirm(SystemClock.elapsedRealtime())) updateOrientation() + } + } else null + onDispose { confirmation?.cancel(); listener.disable() } + } + + fun captureRotation(): Int { + val degrees = orientation.targetDegrees(deviceDegrees) + val rotation = when (degrees) { + 90 -> Surface.ROTATION_90 + 180 -> Surface.ROTATION_180 + 270 -> Surface.ROTATION_270 + else -> Surface.ROTATION_0 + } + LogManager.addLog("INFO", "Capture", "Capture orientation mode=$mode selection=$orientation device=$deviceDegrees " + + "target=$degrees sensorRotation=${camera?.cameraInfo?.getSensorRotationDegrees(rotation)} camera=${lens?.cameraId}") + return rotation + } + DisposableEffect(Unit) { onDispose { closed = true @@ -196,12 +242,13 @@ fun CameraRecordScreen(initialMode: CaptureMode, onSend: (String, CaptureMode) - lens = if (mode == CaptureMode.PHOTO) photoSettings.resolveCamera(lenses) else videoSettings.resolveCamera(lenses) jpegQuality = photoSettings.jpegQuality; bitrate = videoSettings.bitrate codec = StreamVideoCodec.fromId(videoSettings.codec) + orientation = if (mode == CaptureMode.PHOTO) photoSettings.orientation else videoSettings.orientation quality = CaptureResolution.entries.first { it.height == videoSettings.height } val savedCamera = if (mode == CaptureMode.PHOTO) photoSettings.camera else videoSettings.camera if (savedCamera.isNotEmpty() && lens?.cameraId != savedCamera) LogManager.addLog("WARN", "Capture", "Saved camera unavailable mode=$mode saved=$savedCamera selected=${lens?.cameraId}") LogManager.addLog("INFO", "Capture", "Settings restored mode=$mode camera=${lens?.cameraId} type=${lens?.type} " + - "jpegQuality=$jpegQuality resolution=${quality.label} codec=${codec.label} bitrate=$bitrate") + "jpegQuality=$jpegQuality resolution=${quality.label} codec=${codec.label} bitrate=$bitrate orientation=$orientation") } LaunchedEffect(provider, lens, mode) { val ready = provider; val selected = lens @@ -288,8 +335,8 @@ fun CameraRecordScreen(initialMode: CaptureMode, onSend: (String, CaptureMode) - output = file; phase = CapturePhase.CAPTURING; error = false LogManager.addLog("INFO", "Capture", "Photo capture requested camera=${lens?.cameraId} " + "resolution=${resolution?.label} jpegQuality=$jpegQuality") - imageCapture.targetRotation = view.display?.rotation ?: android.view.Surface.ROTATION_0 try { + imageCapture.targetRotation = captureRotation() imageCapture.takePicture(ImageCapture.OutputFileOptions.Builder(file).build(), main, object : ImageCapture.OnImageSavedCallback { override fun onImageSaved(results: ImageCapture.OutputFileResults) { if (closed || output != file) { deleteCache(file); return } @@ -316,8 +363,8 @@ fun CameraRecordScreen(initialMode: CaptureMode, onSend: (String, CaptureMode) - val expectedMime = codec.mime LogManager.addLog("INFO", "Capture", "Video capture requested camera=${lens?.cameraId} codec=$expectedMime " + "resolution=${quality.label} bitrate=$bitrate") - videoCapture.targetRotation = view.display?.rotation ?: android.view.Surface.ROTATION_0 try { + videoCapture.targetRotation = captureRotation() recording = videoCapture.output.prepareRecording(context, FileOutputOptions.Builder(file).build()) .withAudioEnabled().start(main) { event -> if (closed || output != file) { @@ -348,7 +395,11 @@ fun CameraRecordScreen(initialMode: CaptureMode, onSend: (String, CaptureMode) - .first { it.getString(MediaFormat.KEY_MIME)?.startsWith("video/") == true } val mime = video.getString(MediaFormat.KEY_MIME) check(mime == expectedMime) { "Recorded codec mismatch expected=$expectedMime actual=$mime" } - "$mime ${video.getInteger(MediaFormat.KEY_WIDTH)}x${video.getInteger(MediaFormat.KEY_HEIGHT)}" + val rotation = if (video.containsKey(MediaFormat.KEY_ROTATION)) + video.getInteger(MediaFormat.KEY_ROTATION) else 0 + val width = video.getInteger(MediaFormat.KEY_WIDTH) + val height = video.getInteger(MediaFormat.KEY_HEIGHT) + "$mime ${width}x${height} rotation=$rotation" } finally { extractor.release() } } if (closed || output != file) return@launch @@ -430,6 +481,13 @@ fun CameraRecordScreen(initialMode: CaptureMode, onSend: (String, CaptureMode) - } } } + CaptureOrientationControl(orientation, displayDegrees, lens?.type == LensType.SELFIE, + enabled = true, expanded = menu == CameraOption.ORIENTATION, properties = menuProperties, + onExpandedChange = { menu = if (it) CameraOption.ORIENTATION else null }, onChange = { + orientation = it + if (mode == CaptureMode.PHOTO) rememberPhotoSettings() else rememberVideoSettings() + LogManager.addLog("INFO", "Capture", "Orientation selected mode=$mode orientation=$it") + }) Box { if (mode == CaptureMode.VIDEO) { CaptureControlButton(stringResource(R.string.stream_video_codec, codec.label), diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/CaptureControls.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/CaptureControls.kt index 26225e133..0d166452c 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/CaptureControls.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/CaptureControls.kt @@ -5,6 +5,7 @@ import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.ScreenRotation import androidx.compose.material.icons.outlined.Person import androidx.compose.material3.* import androidx.compose.runtime.Composable @@ -19,6 +20,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.heading @@ -27,7 +29,9 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.compose.ui.window.PopupProperties import com.utun.chat.R +import com.utun.chat.data.StreamOrientation import java.text.NumberFormat internal enum class CaptureIconShape { CAMERA, CHIP, GAUGE, SCREEN } @@ -152,3 +156,58 @@ internal fun CaptureOptionItem(label: String, active: Boolean, onClick: () -> Un DropdownMenuItem(text = { Text(label) }, onClick = onClick, leadingIcon = icon, trailingIcon = { if (active) Icon(Icons.Filled.Check, contentDescription = null) }, modifier = Modifier.semantics { selected = active }) } + +/** Общий выбор ориентации фото, видеосообщений и трансляции; маркер показывает верх записываемого кадра. */ +@Composable +internal fun CaptureOrientationControl(orientation: StreamOrientation?, displayDegrees: Int, front: Boolean, + enabled: Boolean, expanded: Boolean, properties: PopupProperties, + onExpandedChange: (Boolean) -> Unit, onChange: (StreamOrientation) -> Unit) { + val auto = orientation == StreamOrientation.AUTO + val degrees = orientation?.degrees?.takeIf { it >= 0 } ?: 0 + fun top(turn: Int) = if (front) (displayDegrees - turn + 360) % 360 else (turn - displayDegrees + 360) % 360 + val label = if (auto) stringResource(R.string.stream_orientation_auto) else stringResource(R.string.stream_orientation, degrees) + Box { + CaptureControlButton(label, enabled, onClick = { onExpandedChange(!expanded) }) { + if (auto) Icon(Icons.Filled.ScreenRotation, contentDescription = null, modifier = Modifier.size(32.dp)) + else CaptureRotationMark(top(degrees), degrees) + } + DropdownMenu(expanded = expanded && enabled, properties = properties, onDismissRequest = { onExpandedChange(false) }) { + CaptureMenuHeader(stringResource(R.string.stream_orientation_title)) + CaptureOptionItem(stringResource(R.string.stream_orientation_auto), auto, + onClick = { onExpandedChange(false); onChange(StreamOrientation.AUTO) }, + icon = { Icon(Icons.Filled.ScreenRotation, contentDescription = null, modifier = Modifier.size(32.dp)) }) + for (option in listOf(StreamOrientation.UPRIGHT, StreamOrientation.RIGHT, StreamOrientation.LEFT)) { + CaptureOptionItem(stringResource(R.string.stream_orientation, option.degrees), orientation == option, + onClick = { onExpandedChange(false); onChange(option) }, + icon = { CaptureRotationMark(top(option.degrees), option.degrees) }) + } + } + } +} + +/** Активное ребро выделено сплошной полосой и треугольником; угол сдвинут от маркера внутрь кадра. */ +@Composable +private fun CaptureRotationMark(top: Int, degrees: Int) { + val frame = LocalContentColor.current + val marker = MaterialTheme.colorScheme.primary.copy(alpha = frame.alpha) + Box(Modifier.size(40.dp, 36.dp), contentAlignment = Alignment.Center) { + Canvas(Modifier.matchParentSize()) { + val left = size.width * 0.2f; val right = size.width * 0.8f + val upper = size.height * 0.04f; val lower = size.height * 0.96f + rotate(top.toFloat()) { + drawRoundRect(frame.copy(alpha = frame.alpha * 0.6f), Offset(left, upper), Size(right - left, lower - upper), + CornerRadius(4.dp.toPx()), style = Stroke(1.5.dp.toPx())) + drawRoundRect(marker, Offset(left, upper), Size(right - left, 4.dp.toPx()), CornerRadius(2.dp.toPx())) + val triangle = Path().apply { + moveTo(center.x - 5.dp.toPx(), upper + 3.dp.toPx()); lineTo(center.x + 5.dp.toPx(), upper + 3.dp.toPx()) + lineTo(center.x, upper + 7.dp.toPx()); close() + } + drawPath(triangle, marker) + } + } + val x = when (top) { 90 -> (-2).dp; 270 -> 2.dp; else -> 0.dp } + val y = when (top) { 0 -> 2.dp; 180 -> (-2).dp; else -> 0.dp } + Text("${degrees}°", Modifier.offset(x, y), fontSize = 10.sp, lineHeight = 12.sp, + fontWeight = FontWeight.Medium, maxLines = 1, softWrap = false) + } +} diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/StreamScreen.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/StreamScreen.kt index bd1c42244..b9fd389f3 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/StreamScreen.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/StreamScreen.kt @@ -17,7 +17,6 @@ import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.* -import androidx.compose.foundation.Canvas import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.horizontalScroll @@ -27,26 +26,18 @@ import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.VolumeOff import androidx.compose.material.icons.automirrored.filled.VolumeUp import androidx.compose.material.icons.filled.PlayArrow -import androidx.compose.material.icons.filled.ScreenRotation import androidx.compose.material.icons.filled.Stop import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.Alignment -import androidx.compose.ui.geometry.CornerRadius -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Size -import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.drawscope.Stroke -import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @@ -66,7 +57,6 @@ import com.utun.chat.data.StreamPreviewTarget import com.utun.chat.data.StreamSource import com.utun.chat.data.StreamCaptureConfig import com.utun.chat.data.StreamCaptureSettings -import com.utun.chat.data.StreamOrientation import com.utun.chat.data.StreamCamera import com.utun.chat.data.StreamCameraModes import com.utun.chat.data.StreamBufferPositions @@ -354,58 +344,10 @@ private fun StreamCaptureToolbar(cameras: List, config: StreamCapt }) } } } - Box { - val auto = config?.orientation == StreamOrientation.AUTO - val degrees = config?.orientation?.degrees?.takeIf { it >= 0 } ?: 0 - val front = camera?.lens?.type == LensType.SELFIE - val top = if (front) (display - degrees + 360) % 360 else (degrees - display + 360) % 360 - val label = if (auto) stringResource(R.string.stream_orientation_auto) else stringResource(R.string.stream_orientation, degrees) - CaptureControlButton(label, enabled && config != null, - onClick = { onMenuChange(if (menu == StreamOption.ORIENTATION) null else StreamOption.ORIENTATION) }) { - if (auto) Icon(Icons.Filled.ScreenRotation, contentDescription = null, modifier = Modifier.size(32.dp)) - else StreamRotationMark(top, degrees) - } - DropdownMenu(expanded = menu == StreamOption.ORIENTATION && enabled, properties = menuProperties, - onDismissRequest = { if (menu == StreamOption.ORIENTATION) onMenuChange(null) }) { - CaptureMenuHeader(stringResource(R.string.stream_orientation_title)) - CaptureOptionItem(stringResource(R.string.stream_orientation_auto), auto, - onClick = { onMenuChange(null); config?.let { onChange(it.copy(orientation = StreamOrientation.AUTO)) } }, - icon = { Icon(Icons.Filled.ScreenRotation, contentDescription = null, modifier = Modifier.size(32.dp)) }) - for (option in listOf(StreamOrientation.UPRIGHT, StreamOrientation.RIGHT, StreamOrientation.LEFT)) { - val optionTop = if (front) (display - option.degrees + 360) % 360 else (option.degrees - display + 360) % 360 - CaptureOptionItem(stringResource(R.string.stream_orientation, option.degrees), config?.orientation == option, - onClick = { onMenuChange(null); config?.let { onChange(it.copy(orientation = option)) } }, - icon = { StreamRotationMark(optionTop, option.degrees) }) - } - } - } - } -} - -/** Активное ребро выделено сплошной полосой и треугольником; угол сдвинут от маркера внутрь кадра. */ -@Composable -private fun StreamRotationMark(top: Int, degrees: Int) { - val frame = LocalContentColor.current - val marker = MaterialTheme.colorScheme.primary.copy(alpha = frame.alpha) - Box(Modifier.size(40.dp, 36.dp), contentAlignment = Alignment.Center) { - Canvas(Modifier.matchParentSize()) { - val left = size.width * 0.2f; val right = size.width * 0.8f - val upper = size.height * 0.04f; val lower = size.height * 0.96f - rotate(top.toFloat()) { - drawRoundRect(frame.copy(alpha = frame.alpha * 0.6f), Offset(left, upper), Size(right - left, lower - upper), - CornerRadius(4.dp.toPx()), style = Stroke(1.5.dp.toPx())) - drawRoundRect(marker, Offset(left, upper), Size(right - left, 4.dp.toPx()), CornerRadius(2.dp.toPx())) - val triangle = Path().apply { - moveTo(center.x - 5.dp.toPx(), upper + 3.dp.toPx()); lineTo(center.x + 5.dp.toPx(), upper + 3.dp.toPx()) - lineTo(center.x, upper + 7.dp.toPx()); close() - } - drawPath(triangle, marker) - } - } - val x = when (top) { 90 -> (-2).dp; 270 -> 2.dp; else -> 0.dp } - val y = when (top) { 0 -> 2.dp; 180 -> (-2).dp; else -> 0.dp } - Text("${degrees}°", Modifier.offset(x, y), fontSize = 10.sp, lineHeight = 12.sp, - fontWeight = FontWeight.Medium, maxLines = 1, softWrap = false) + CaptureOrientationControl(config?.orientation, display, camera?.lens?.type == LensType.SELFIE, + enabled = enabled && config != null, expanded = menu == StreamOption.ORIENTATION, properties = menuProperties, + onExpandedChange = { onMenuChange(if (it) StreamOption.ORIENTATION else null) }, + onChange = { option -> config?.let { onChange(it.copy(orientation = option)) } }) } } diff --git a/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/VideoPlayerScreen.kt b/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/VideoPlayerScreen.kt index f73512fd0..32178cfdb 100644 --- a/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/VideoPlayerScreen.kt +++ b/tools/chatgui-android/app/src/main/java/com/utun/chat/ui/screens/VideoPlayerScreen.kt @@ -10,7 +10,6 @@ import android.content.pm.ActivityInfo import android.graphics.SurfaceTexture import android.media.MediaMetadataRetriever import android.media.MediaPlayer -import android.view.OrientationEventListener import android.view.Surface import android.view.TextureView import androidx.compose.animation.AnimatedVisibility @@ -55,7 +54,7 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.withContext -private data class VideoInfo(val width: Int, val height: Int, val rotation: Int) { +internal data class VideoInfo(val width: Int, val height: Int, val rotation: Int) { val displayWidth: Int get() = if (rotation == 90 || rotation == 270) height else width val displayHeight: Int get() = if (rotation == 90 || rotation == 270) width else height val aspect: Float get() = if (displayHeight > 0) displayWidth.toFloat() / displayHeight else 0f @@ -131,29 +130,19 @@ fun VideoPlayerScreen(filePath: String, onClose: () -> Unit) { val act = context.findActivity() val prev = act?.requestedOrientation val info = videoInfo - var oel: OrientationEventListener? = null if (act != null && info != null && info.displayWidth > 0 && info.displayHeight > 0) { - if (info.displayWidth > info.displayHeight) { - /* landscape: determine side from sensor once, then lock */ - oel = object : OrientationEventListener(context) { - override fun onOrientationChanged(angle: Int) { - if (angle == ORIENTATION_UNKNOWN) return - val reverse = angle in 45..134 - val orient = if (reverse) ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE - else ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE - LogManager.addLog("INFO", "VideoPlayer", "auto-orient sensor=$angle -> ${if (reverse) "REVERSE_LANDSCAPE" else "LANDSCAPE"} (prev=$prev)") - act.requestedOrientation = orient - disable() - } - } - oel.enable() - } else { - LogManager.addLog("INFO", "VideoPlayer", "auto-orient -> PORTRAIT (prev=$prev)") - act.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT + val orientation = when { + info.displayWidth > info.displayHeight -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE + info.displayHeight > info.displayWidth -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT + else -> prev + } + if (orientation != null) { + act.requestedOrientation = orientation + LogManager.addLog("INFO", "VideoPlayer", "Fit screen video=${info.displayWidth}x${info.displayHeight} " + + "metadataRotation=${info.rotation} requested=$orientation previous=$prev") } } onDispose { - oel?.disable() if (act != null && prev != null) { act.requestedOrientation = prev LogManager.addLog("INFO", "VideoPlayer", "restore orientation $prev") @@ -243,10 +232,9 @@ fun VideoPlayerScreen(filePath: String, onClose: () -> Unit) { fun flipLandscape() { onInteraction() val act = context.findActivity() ?: return - val cur = act.requestedOrientation - val newOrient = if (cur == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) - ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE - else ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE + val rotation = act.windowManager.defaultDisplay.rotation + val reverse = rotation == Surface.ROTATION_180 || rotation == Surface.ROTATION_270 + val newOrient = if (reverse) ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE else ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE LogManager.addLog("INFO", "VideoPlayer", "flip 180 -> $newOrient") act.requestedOrientation = newOrient } diff --git a/tools/chatgui-android/app/src/test/java/com/utun/chat/data/CameraCaptureSettingsTest.kt b/tools/chatgui-android/app/src/test/java/com/utun/chat/data/CameraCaptureSettingsTest.kt index 475a115a8..57e0bcc91 100644 --- a/tools/chatgui-android/app/src/test/java/com/utun/chat/data/CameraCaptureSettingsTest.kt +++ b/tools/chatgui-android/app/src/test/java/com/utun/chat/data/CameraCaptureSettingsTest.kt @@ -14,6 +14,8 @@ class CameraCaptureSettingsTest { assertEquals(85, PhotoCaptureSettings().jpegQuality) assertEquals(selfie, VideoCaptureSettings().resolveCamera(lenses)) assertEquals(720, VideoCaptureSettings().height) + assertEquals(StreamOrientation.AUTO, PhotoCaptureSettings().orientation) + assertEquals(StreamOrientation.AUTO, VideoCaptureSettings().orientation) } @Test fun savedCamerasOverrideDefaultsAndMissingCamerasFallBackPerMode() { diff --git a/tools/chatgui-android/app/src/test/java/com/utun/chat/data/StreamOrientationTest.kt b/tools/chatgui-android/app/src/test/java/com/utun/chat/data/StreamOrientationTest.kt index d3da805b2..82edc5e28 100644 --- a/tools/chatgui-android/app/src/test/java/com/utun/chat/data/StreamOrientationTest.kt +++ b/tools/chatgui-android/app/src/test/java/com/utun/chat/data/StreamOrientationTest.kt @@ -35,6 +35,17 @@ class StreamOrientationTest { } } + @Test fun cameraXTargetMatchesStreamForFrontAndRearSensors() { + for (option in StreamOrientation.entries) for (device in listOf(0, 90, 180, 270)) { + val target = option.targetDegrees(device) + assertEquals(if (option == StreamOrientation.AUTO) (360 - device) % 360 else option.degrees, target) + for (sensor in listOf(0, 90, 180, 270)) { + assertEquals((sensor - target + 360) % 360, option.sensorRotation(sensor, false, device)) + assertEquals((sensor + target) % 360, option.sensorRotation(sensor, true, device)) + } + } + } + @Test fun newCaptureUsesAutoByDefault() { val mode = StreamCaptureMode("camera", 1280, 720, 30, 30, false, "encoder", 2_000_000) assertEquals(StreamOrientation.AUTO, StreamCaptureConfig(mode).orientation) diff --git a/tools/chatgui-android/app/src/test/java/com/utun/chat/ui/screens/VideoPlayerInfoTest.kt b/tools/chatgui-android/app/src/test/java/com/utun/chat/ui/screens/VideoPlayerInfoTest.kt new file mode 100644 index 000000000..d44eca3e3 --- /dev/null +++ b/tools/chatgui-android/app/src/test/java/com/utun/chat/ui/screens/VideoPlayerInfoTest.kt @@ -0,0 +1,24 @@ +package com.utun.chat.ui.screens + +import org.junit.Assert.assertEquals +import org.junit.Test + +class VideoPlayerInfoTest { + @Test fun portraitRecordingUsesRotatedDimensionsForScreenAndFit() { + for (rotation in listOf(90, 270)) { + val info = VideoInfo(1280, 720, rotation) + assertEquals(720, info.displayWidth) + assertEquals(1280, info.displayHeight) + assertEquals(9f / 16f, info.aspect, 0.0001f) + } + } + + @Test fun landscapeRecordingKeepsDimensionsForBothDirections() { + for (rotation in listOf(0, 180)) { + val info = VideoInfo(1280, 720, rotation) + assertEquals(1280, info.displayWidth) + assertEquals(720, info.displayHeight) + assertEquals(16f / 9f, info.aspect, 0.0001f) + } + } +}