From e8cd196e1a152b2b3ccc0a0d7638e5d9634e40c5 Mon Sep 17 00:00:00 2001 From: zhoubinjia Date: Fri, 30 Jan 2026 18:21:42 +0800 Subject: [PATCH 1/2] feat: live photo --- .../mycamera/camera/Camera2Controller.kt | 32 ++ .../com/hinnka/mycamera/camera/CameraState.kt | 1 + .../data/UserPreferencesRepository.kt | 16 +- .../hinnka/mycamera/gallery/PhotoManager.kt | 246 ++++++--- .../livephoto/CircularVideoRecorder.kt | 121 +++++ .../livephoto/HardwareLutVideoRenderer.kt | 194 +++++++ .../mycamera/livephoto/LivePhotoRecorder.kt | 339 +++++++++++++ .../mycamera/livephoto/MotionPhotoWriter.kt | 473 ++++++++++++++++++ .../com/hinnka/mycamera/lut/LutRenderer.kt | 192 ++++++- .../java/com/hinnka/mycamera/lut/Shaders.kt | 425 ++++++++-------- .../mycamera/ui/camera/CameraGLSurfaceView.kt | 8 + .../mycamera/ui/camera/CameraPreviewGL.kt | 7 + .../hinnka/mycamera/ui/camera/CameraScreen.kt | 45 +- .../mycamera/ui/camera/CameraTopSheet.kt | 19 + .../mycamera/ui/settings/SettingsScreen.kt | 13 + .../java/com/hinnka/mycamera/utils/PLog.kt | 14 +- .../mycamera/viewmodel/CameraViewModel.kt | 54 ++ app/src/main/res/values-zh/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + 19 files changed, 1925 insertions(+), 278 deletions(-) create mode 100644 app/src/main/java/com/hinnka/mycamera/livephoto/CircularVideoRecorder.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/livephoto/HardwareLutVideoRenderer.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/livephoto/LivePhotoRecorder.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/livephoto/MotionPhotoWriter.kt diff --git a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt index 07b75697..6ec1a717 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -23,6 +23,10 @@ import com.hinnka.mycamera.utils.YuvProcessor import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import com.hinnka.mycamera.livephoto.LivePhotoRecorder +import com.hinnka.mycamera.lut.LutConfig +import com.hinnka.mycamera.model.ColorRecipeParams +import java.io.File import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.Executors import java.util.concurrent.atomic.AtomicInteger @@ -113,6 +117,9 @@ class Camera2Controller(private val context: Context) { private val _state = MutableStateFlow(CameraState()) val state: StateFlow = _state.asStateFlow() + // Live Photo 录制器 + val livePhotoRecorder = LivePhotoRecorder(context) + // 缓存 CaptureResult 和 Image 用于配对 (timestamp -> Data) private val pendingResults = ConcurrentHashMap() private val pendingImages = ConcurrentHashMap() @@ -140,6 +147,9 @@ class Camera2Controller(private val context: Context) { var onPreviewFrameCaptured: ((Bitmap) -> Unit)? = null private var shouldCapturePreviewFrame = false + // Live Photo 录制状态 + var onLivePhotoVideoCaptured: ((java.io.File, Long) -> Unit)? = null + var rawPreviewFrame: Bitmap? = null // 相机错误回调(供上层处理错误恢复) @@ -2334,4 +2344,26 @@ class Camera2Controller(private val context: Context) { stopBackgroundThread() cameraDiscovery.clearCache() } + + /** + * 设置是否启用 Live Photo + */ + fun setUseLivePhoto(enabled: Boolean) { + _state.value = _state.value.copy(useLivePhoto = enabled) + if (enabled) { + livePhotoRecorder.startRecording() + } else { + livePhotoRecorder.stopRecording() + } + } + + /** + * 执行 Live Photo 快照并开始后台录制 + */ + fun captureLivePhoto(lutConfig: LutConfig?, colorRecipeParams: ColorRecipeParams?) { + livePhotoRecorder.snapshot() + livePhotoRecorder.recordVideo(lutConfig, colorRecipeParams) { file, timestamp -> + onLivePhotoVideoCaptured?.invoke(file, timestamp) + } + } } diff --git a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt index 94c7aea6..765bded1 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt @@ -175,6 +175,7 @@ data class CameraState( val multiFrameCount: Int = 0, val useSuperResolution: Boolean = false, val useRaw: Boolean = false, + val useLivePhoto: Boolean = false, ) { /** * 是否全自动曝光 diff --git a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt index ef61d272..93183faf 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt @@ -59,7 +59,8 @@ data class UserPreferences( val useMultiFrame: Boolean = false, // 是否使用多帧合成 val multiFrameCount: Int = 8, // 多帧合成帧数 val useSuperResolution: Boolean = false, // 是否使用超分辨率 - val rawEngine: RawEngine = RawEngine.NATIVE // RAW处理引擎 + val rawEngine: RawEngine = RawEngine.NATIVE, // RAW处理引擎 + val useLivePhoto: Boolean = false // 是否启用 Live Photo (Motion Photo) ) /** @@ -105,6 +106,7 @@ class UserPreferencesRepository(private val context: Context) { private val MULTI_FRAME_COUNT = intPreferencesKey("multi_frame_count") private val USE_SUPER_RESOLUTION = booleanPreferencesKey("use_super_resolution") private val RAW_ENGINE = stringPreferencesKey("raw_engine") + private val USE_LIVE_PHOTO = booleanPreferencesKey("use_live_photo") } /** @@ -144,7 +146,8 @@ class UserPreferencesRepository(private val context: Context) { useSuperResolution = preferences[USE_SUPER_RESOLUTION] ?: false, rawEngine = RawEngine.valueOf( preferences[RAW_ENGINE] ?: RawEngine.NATIVE.name - ) + ), + useLivePhoto = preferences[USE_LIVE_PHOTO] ?: false ) } @@ -433,4 +436,13 @@ class UserPreferencesRepository(private val context: Context) { preferences[RAW_ENGINE] = engine.name } } + + /** + * 保存是否启用 Live Photo + */ + suspend fun saveUseLivePhoto(enabled: Boolean) { + context.dataStore.edit { preferences -> + preferences[USE_LIVE_PHOTO] = enabled + } + } } diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt index f5a52cee..1b195471 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt @@ -23,6 +23,7 @@ import androidx.core.graphics.createBitmap import androidx.exifinterface.media.ExifInterface import com.hinnka.mycamera.camera.AspectRatio import com.hinnka.mycamera.data.RawEngine +import com.hinnka.mycamera.livephoto.MotionPhotoWriter import com.hinnka.mycamera.processor.MultiFrameStacker import com.hinnka.mycamera.raw.RawDemosaicProcessor import com.hinnka.mycamera.utils.BitmapUtils @@ -48,6 +49,7 @@ object PhotoManager { private const val PHOTOS_DIR = "photos" private const val PHOTO_FILE = "original.jpg" private const val YUV_FILE = "original.jxl" + private const val VIDEO_FILE = "video.mp4" private const val DNG_FILE = "original.dng" private const val METADATA_FILE = "metadata.json" private const val THUMBNAIL_FILE = "thumbnail.jpg" @@ -111,8 +113,9 @@ object PhotoManager { processedBitmap ?: return@withContext // 保存到指定目录 + // Use MVIMG naming convention (classic Google Camera) as suggested by reference implementation val filename = - "PhotonCamera_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())}.jpg" + "MVIMG_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())}.jpg" val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, filename) put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg") @@ -124,28 +127,74 @@ object PhotoManager { contentValues ) - uri?.let { - context.contentResolver.openOutputStream(it)?.use { outputStream -> - processedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream) - } + uri?.let { uri -> + val videoFile = File(getPhotoDir(context, id), VIDEO_FILE) + val isLivePhoto = videoFile.exists() + + val tempExportFile = File(context.cacheDir, "temp_export_${System.nanoTime()}.jpg") + try { + FileOutputStream(tempExportFile).use { out -> + processedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out) + } - // 写入 EXIF 信息 - context.contentResolver.openFileDescriptor(it, "rw")?.use { pfd -> ExifWriter.writeExif( - pfd.fileDescriptor, metadata.toCaptureInfo().copy( + tempExportFile, metadata.toCaptureInfo().copy( imageWidth = processedBitmap.width, imageHeight = processedBitmap.height ) ) + + if (isLivePhoto) { + val tempMotionPhotoFile = File(context.cacheDir, "temp_motion_${System.nanoTime()}.jpg") + try { + val presentationTimestampUs = 1_500_000L + PLog.d( + TAG, + "Attempting to create Motion Photo for export: JPEG=${tempExportFile.length()}, Video=${videoFile.length()}" + ) + + val success = MotionPhotoWriter.write( + tempExportFile.absolutePath, + videoFile.absolutePath, + tempMotionPhotoFile.absolutePath, + presentationTimestampUs + ) + + PLog.d(TAG, "MotionPhotoWriter result: $success") + + context.contentResolver.openOutputStream(uri)?.use { outputStream -> + if (success) { + tempMotionPhotoFile.inputStream().use { input -> input.copyTo(outputStream) } + PLog.d( + TAG, + "Exported Live Photo successfully: ${tempMotionPhotoFile.length()} bytes" + ) + } else { + // Fallback to normal JPEG (with EXIF) + PLog.w(TAG, "Motion Photo synthesis failed, falling back to JPEG") + tempExportFile.inputStream().use { input -> input.copyTo(outputStream) } + } + } + } finally { + tempMotionPhotoFile.delete() + } + } else { + // 3b. Normal Export: Copy Temp File (with EXIF) to MediaStore + context.contentResolver.openOutputStream(uri)?.use { outputStream -> + tempExportFile.inputStream().use { input -> input.copyTo(outputStream) } + } + } + } finally { + tempExportFile.delete() } - // 保存导出的 URI 到元数据 + // Save exported URI to metadata val currentMetadata = loadMetadata(context, id) ?: metadata val updatedMetadata = currentMetadata.copy( - exportedUris = currentMetadata.exportedUris + it.toString() + exportedUris = currentMetadata.exportedUris + uri.toString() ) saveMetadata(context, id, updatedMetadata) - PLog.d(TAG, "Exported URI saved: $it for photo $id") + PLog.d(TAG, "Exported URI saved: $uri for photo $id") } processedBitmap.recycle() @@ -162,45 +211,46 @@ object PhotoManager { } } - suspend fun exportDng(context: Context, data: ByteArray, metadata: PhotoMetadata) = withContext(Dispatchers.IO) { - try { - val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US) - .format(Date()) - val dngFilename = "PhotonCamera_${timestamp}.dng" - val dngContentValues = ContentValues().apply { - put(MediaStore.MediaColumns.DISPLAY_NAME, dngFilename) - put(MediaStore.MediaColumns.MIME_TYPE, "image/x-adobe-dng") - put( - MediaStore.MediaColumns.RELATIVE_PATH, - Environment.DIRECTORY_DCIM + "/PhotonCamera" - ) - } - - val dngUri = context.contentResolver.insert( - MediaStore.Images.Media.EXTERNAL_CONTENT_URI, - dngContentValues - ) - - dngUri?.let { uri -> - context.contentResolver.openOutputStream(uri)?.use { outputStream -> - outputStream.write(data) - } - PLog.d(TAG, "DNG exported: $uri") - - val photoId = getPhotoIds(context).firstOrNull() - if (photoId != null) { - val currentMetadata = loadMetadata(context, photoId) ?: metadata - val updatedMetadata = currentMetadata.copy( - exportedUris = currentMetadata.exportedUris + uri.toString() + suspend fun exportDng(context: Context, data: ByteArray, metadata: PhotoMetadata) = + withContext(Dispatchers.IO) { + try { + val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US) + .format(Date()) + val dngFilename = "PhotonCamera_${timestamp}.dng" + val dngContentValues = ContentValues().apply { + put(MediaStore.MediaColumns.DISPLAY_NAME, dngFilename) + put(MediaStore.MediaColumns.MIME_TYPE, "image/x-adobe-dng") + put( + MediaStore.MediaColumns.RELATIVE_PATH, + Environment.DIRECTORY_DCIM + "/PhotonCamera" ) - saveMetadata(context, photoId, updatedMetadata) - PLog.d(TAG, "Exported URI saved: $uri") } + + val dngUri = context.contentResolver.insert( + MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + dngContentValues + ) + + dngUri?.let { uri -> + context.contentResolver.openOutputStream(uri)?.use { outputStream -> + outputStream.write(data) + } + PLog.d(TAG, "DNG exported: $uri") + + val photoId = getPhotoIds(context).firstOrNull() + if (photoId != null) { + val currentMetadata = loadMetadata(context, photoId) ?: metadata + val updatedMetadata = currentMetadata.copy( + exportedUris = currentMetadata.exportedUris + uri.toString() + ) + saveMetadata(context, photoId, updatedMetadata) + PLog.d(TAG, "Exported URI saved: $uri") + } + } + } catch (e: Exception) { + PLog.e(TAG, "Failed to export DNG", e) } - } catch (e: Exception) { - PLog.e(TAG, "Failed to export DNG", e) } - } /** @@ -224,6 +274,7 @@ object PhotoManager { sharpeningValue: Float, noiseReductionValue: Float, chromaNoiseReductionValue: Float, + livePhotoVideoDeferred: Deferred? = null, onProcessingComplete: (() -> Unit)? = null ): String? { return try { @@ -281,16 +332,50 @@ object PhotoManager { previewBitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStream) } tempFile.renameTo(photoFile) - if (shouldAutoSave) { - exportPhoto( - context, - photoId, - photoProcessor, - metadataWithInfo, - sharpeningValue, - noiseReductionValue, - chromaNoiseReductionValue - ) + + // 处理 Live Photo 合成 + livePhotoVideoDeferred?.await()?.let { videoFile -> + Log.d(TAG, "savePhoto: livePhotoVideoDeferred") + val presentationTimestampUs = 1_500_000L // 假设 1.5s 缓冲 + val motionPhotoFile = File(photoDir, "motion_photo.jpg") + if (MotionPhotoWriter.write( + photoFile.absolutePath, + videoFile.absolutePath, + motionPhotoFile.absolutePath, + presentationTimestampUs + ) + ) { + motionPhotoFile.renameTo(photoFile) + // 保留原始视频文件以供后续再次导出 + val savedVideoFile = File(photoDir, VIDEO_FILE) + if (savedVideoFile.exists()) savedVideoFile.delete() + + var renameSuccess = videoFile.renameTo(savedVideoFile) + if (!renameSuccess) { + PLog.w(TAG, "Video rename failed, trying copy and delete") + try { + videoFile.copyTo(savedVideoFile, overwrite = true) + videoFile.delete() + renameSuccess = true + } catch (e: Exception) { + PLog.e(TAG, "Failed to move video file", e) + } + } + PLog.d(TAG, "Video moved to ${savedVideoFile.name}: $renameSuccess") + PLog.d(TAG, "Motion Photo synthesized for $photoId") + + if (shouldAutoSave) { + exportPhoto( + context, + photoId, + photoProcessor, + metadataWithInfo, + sharpeningValue, + noiseReductionValue, + chromaNoiseReductionValue + ) + } + } } } } finally { @@ -305,7 +390,13 @@ object PhotoManager { return null } val dimensions = - BitmapUtils.calculateProcessedRect(image.width, image.height, aspectRatio, cropRegion, rotation) + BitmapUtils.calculateProcessedRect( + image.width, + image.height, + aspectRatio, + cropRegion, + rotation + ) processingScope.launch(Dispatchers.IO) { try { photoFile.createNewFile() @@ -406,6 +497,7 @@ object PhotoManager { noiseReductionValue: Float, chromaNoiseReductionValue: Float, useSuperResolution: Boolean = false, + livePhotoVideoDeferred: Deferred? = null, onProcessingComplete: (() -> Unit)? = null ): String? { return try { @@ -476,7 +568,12 @@ object PhotoManager { val scaledHeight = images[0].height * scale var cropRegion = captureResult.get(CaptureResult.SCALER_CROP_REGION) if (useSuperResolution && cropRegion != null) { - cropRegion = Rect(cropRegion.left * 2, cropRegion.top * 2, cropRegion.right * 2, cropRegion.bottom * 2) + cropRegion = Rect( + cropRegion.left * 2, + cropRegion.top * 2, + cropRegion.right * 2, + cropRegion.bottom * 2 + ) } // 保存元数据 @@ -535,6 +632,39 @@ object PhotoManager { result.compress(Bitmap.CompressFormat.JPEG, 95, outputStream) } tempFile.renameTo(photoFile) + + // 处理 Live Photo 合成 + livePhotoVideoDeferred?.await()?.let { videoFile -> + val presentationTimestampUs = 1_500_000L // 假设 1.5s 缓冲 + val motionPhotoFile = File(photoDir, "motion_photo.jpg") + if (MotionPhotoWriter.write( + photoFile.absolutePath, + videoFile.absolutePath, + motionPhotoFile.absolutePath, + presentationTimestampUs + ) + ) { + motionPhotoFile.renameTo(photoFile) + // 保留原始视频文件以供后续再次导出 + val savedVideoFile = File(photoDir, VIDEO_FILE) + if (savedVideoFile.exists()) savedVideoFile.delete() + + var renameSuccess = videoFile.renameTo(savedVideoFile) + if (!renameSuccess) { + PLog.w(TAG, "Video rename failed in stacked, trying copy and delete") + try { + videoFile.copyTo(savedVideoFile, overwrite = true) + videoFile.delete() + renameSuccess = true + } catch (e: Exception) { + PLog.e(TAG, "Failed to move video file in stacked", e) + } + } + PLog.d(TAG, "Video moved to ${savedVideoFile.name} in stacked: $renameSuccess") + PLog.d(TAG, "Motion Photo synthesized for stacked $photoId") + } + } + result.recycle() // Auto Save if (shouldAutoSave) { diff --git a/app/src/main/java/com/hinnka/mycamera/livephoto/CircularVideoRecorder.kt b/app/src/main/java/com/hinnka/mycamera/livephoto/CircularVideoRecorder.kt new file mode 100644 index 00000000..4bafe840 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/livephoto/CircularVideoRecorder.kt @@ -0,0 +1,121 @@ +package com.hinnka.mycamera.livephoto + +import android.media.MediaCodec +import com.hinnka.mycamera.utils.PLog +import java.nio.ByteBuffer +import java.util.concurrent.ConcurrentLinkedDeque + +/** + * 循环视频采样缓冲器 + * + * 存储由 MediaCodec 编码后的视频样本 (Samples)。 + * 相比存储原始像素,这种方式内存占用极低 (几百 KB vs 几百 MB),彻底解决 OOM 问题。 + */ +class CircularVideoRecorder( + private val bufferDurationMs: Long = 1500L +) { + /** + * 编码后的视频样本 + * @param data H.264/HEVC 编码数据 + * @param info 媒体缓存信息 (包含时间戳、关键帧标志等) + */ + data class Sample( + val data: ByteArray, + val info: MediaCodec.BufferInfo + ) + + private val samples = ConcurrentLinkedDeque() + + @Volatile + var isRecording: Boolean = false + private set + + /** + * 开始缓存 + */ + fun startRecording() { + samples.clear() + isRecording = true + } + + /** + * 停止缓存 + */ + fun stopRecording() { + isRecording = false + } + + /** + * 添加编码后的样本 + */ + fun addSample(byteBuffer: ByteBuffer, info: MediaCodec.BufferInfo) { + if (!isRecording) return + + //PLog.v("CircularVideoRecorder", "Adding sample ts=${info.presentationTimeUs}, size=${info.size}") + + // 拷贝数据,因为 ByteBuffer 会被 MediaCodec 回收 + val data = ByteArray(info.size) + byteBuffer.position(info.offset) + byteBuffer.get(data) + + // 拷贝 BufferInfo + val sampleInfo = MediaCodec.BufferInfo() + sampleInfo.set(0, info.size, info.presentationTimeUs, info.flags) + + samples.addLast(Sample(data, sampleInfo)) + + // 维持循环缓冲:移除超过时长的旧样本 + // 注意:理想情况下应保留到最近的一个 I 帧,这里先按时间简单裁剪 + trimStorage() + } + + private fun trimStorage() { + if (samples.isEmpty()) return + + val lastTimestamp = samples.last().info.presentationTimeUs + val threshold = lastTimestamp - bufferDurationMs * 1000 + + while (samples.size > 1) { + val first = samples.first() + if (first.info.presentationTimeUs < threshold) { + samples.pollFirst() + } else { + break + } + } + } + + /** + * 获取最新样本的时间戳 + */ + fun getLatestTimestamp(): Long? { + return samples.peekLast()?.info?.presentationTimeUs + } + + /** + * 获取当前所有缓存的样本副本 + */ + fun snapshot(): List = samples.toList() + + /** + * 获取指定时间戳之后的样本 + */ + fun getSamplesAfter(timestampUs: Long): List { + return samples.filter { it.info.presentationTimeUs > timestampUs } + } + + /** + * 清空 + */ + fun clear() { + samples.clear() + } + + /** + * 释放 (此处不需要释放 DirectBuffer) + */ + fun release() { + isRecording = false + samples.clear() + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/livephoto/HardwareLutVideoRenderer.kt b/app/src/main/java/com/hinnka/mycamera/livephoto/HardwareLutVideoRenderer.kt new file mode 100644 index 00000000..518905c2 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/livephoto/HardwareLutVideoRenderer.kt @@ -0,0 +1,194 @@ +package com.hinnka.mycamera.livephoto + +import android.opengl.EGL14 +import android.opengl.EGLConfig +import android.opengl.EGLContext +import android.opengl.EGLDisplay +import android.opengl.EGLExt +import android.opengl.EGLSurface +import android.opengl.GLES30 +import android.view.Surface +import com.hinnka.mycamera.lut.GlUtils.compileShader +import com.hinnka.mycamera.lut.LutConfig +import com.hinnka.mycamera.lut.Shaders +import com.hinnka.mycamera.model.ColorRecipeParams +import com.hinnka.mycamera.utils.PLog +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.nio.FloatBuffer +import java.nio.ShortBuffer + +/** + * 视频帧渲染引擎 (重构版) + * + * 专门负责将纹理(GL_TEXTURE_2D)渲染到 MediaCodec 的 InputSurface。 + * 此版本不再处理 LUT 和色彩配方,而是直接接受已经处理好的 FBO 纹理。 + */ +class HardwareLutVideoRenderer( + private val width: Int, + private val height: Int, + lutConfig: LutConfig?, // 保留参数以兼容现有调用 + colorRecipeParams: ColorRecipeParams? // 保留参数 +) { + companion object { + private const val TAG = "HardwareLutVideoRenderer" + } + + // EGL + private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY + private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT + private var eglSurface: EGLSurface = EGL14.EGL_NO_SURFACE + + // OpenGL + private var shaderProgram: Int = 0 + private var vertexBuffer: FloatBuffer? = null + private var texCoordBuffer: FloatBuffer? = null + private var indexBuffer: ShortBuffer? = null + + // Cached locations + private var uMVPMatrixLoc = -1 + private var uSTMatrixLoc = -1 + private var uCameraTextureLoc = -1 + private var aPositionLoc = -1 + private var aTexCoordLoc = -1 + + // 空实现,不再需要 + fun updateConfig(lutConfig: LutConfig?, colorRecipeParams: ColorRecipeParams?) { + // no-op + } + + /** + * 初始化 EGL 环境并绑定到输出 Surface + * @param sharedContext 共享上下文 + */ + fun initialize(surface: Surface, sharedContext: EGLContext = EGL14.EGL_NO_CONTEXT) { + eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY) + EGL14.eglInitialize(eglDisplay, IntArray(2), 0, IntArray(2), 1) + + val configAttribs = intArrayOf( + EGL14.EGL_RED_SIZE, 8, + EGL14.EGL_GREEN_SIZE, 8, + EGL14.EGL_BLUE_SIZE, 8, + EGL14.EGL_ALPHA_SIZE, 8, + EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT, + 0x3142, 1, // EGL_RECORDABLE_ANDROID + EGL14.EGL_NONE + ) + val configs = arrayOfNulls(1) + val numConfigs = IntArray(1) + if (!EGL14.eglChooseConfig(eglDisplay, configAttribs, 0, configs, 0, 1, numConfigs, 0)) { + PLog.e(TAG, "eglChooseConfig failed") + return + } + + eglContext = EGL14.eglCreateContext( + eglDisplay, configs[0], sharedContext, + intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 3, EGL14.EGL_NONE), 0 + ) + + eglSurface = EGL14.eglCreateWindowSurface( + eglDisplay, configs[0], surface, + intArrayOf(EGL14.EGL_NONE), 0 + ) + + makeCurrent() + initGL() + PLog.d(TAG, "EGL initialized for Texture Copy") + } + + private fun makeCurrent() { + EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext) + } + + private fun initGL() { + // 使用 COPY_2D Shader + val vs = compileShader(GLES30.GL_VERTEX_SHADER, Shaders.VERTEX_SHADER) + val fs = compileShader(GLES30.GL_FRAGMENT_SHADER, Shaders.FRAGMENT_SHADER_COPY_2D) + + shaderProgram = GLES30.glCreateProgram().apply { + GLES30.glAttachShader(this, vs) + GLES30.glAttachShader(this, fs) + GLES30.glLinkProgram(this) + } + + uMVPMatrixLoc = GLES30.glGetUniformLocation(shaderProgram, "uMVPMatrix") + uSTMatrixLoc = GLES30.glGetUniformLocation(shaderProgram, "uSTMatrix") + uCameraTextureLoc = GLES30.glGetUniformLocation(shaderProgram, "uCameraTexture") + aPositionLoc = GLES30.glGetAttribLocation(shaderProgram, "aPosition") + aTexCoordLoc = GLES30.glGetAttribLocation(shaderProgram, "aTexCoord") + + // 准备定点数据 + vertexBuffer = ByteBuffer.allocateDirect(Shaders.FULL_QUAD_VERTICES.size * 4).run { + order(ByteOrder.nativeOrder()).asFloatBuffer().put(Shaders.FULL_QUAD_VERTICES).apply { position(0) } + } + texCoordBuffer = ByteBuffer.allocateDirect(Shaders.TEXTURE_COORDS.size * 4).run { + order(ByteOrder.nativeOrder()).asFloatBuffer().put(Shaders.TEXTURE_COORDS).apply { position(0) } + } + indexBuffer = ByteBuffer.allocateDirect(Shaders.DRAW_ORDER.size * 2).run { + order(ByteOrder.nativeOrder()).asShortBuffer().put(Shaders.DRAW_ORDER).apply { position(0) } + } + } + + /** + * 渲染一帧 + * @param textureId 2D 纹理 ID (GL_TEXTURE_2D) + */ + fun renderFrame(textureId: Int, stMatrix: FloatArray, timestampUs: Long) { + val oldDisplay = EGL14.eglGetCurrentDisplay() + val oldDrawSurface = EGL14.eglGetCurrentSurface(EGL14.EGL_DRAW) + val oldReadSurface = EGL14.eglGetCurrentSurface(EGL14.EGL_READ) + val oldContext = EGL14.eglGetCurrentContext() + + makeCurrent() + + GLES30.glViewport(0, 0, width, height) + GLES30.glClearColor(0.0f, 0.0f, 0.0f, 1.0f) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + GLES30.glUseProgram(shaderProgram) + + // 传入矩阵 + // 因为我们直接拷贝 FBO,stMatrix 可能需要重置为 Identity,或者根据 FBO 坐标系调整 + // FBO 纹理通常是标准坐标 (0,0)-(1,1) 上下可能翻转 + // 这里暂时传递 stMatrix,如果 FBO 自带变换则可能需要 Identity + if (uSTMatrixLoc != -1) GLES30.glUniformMatrix4fv(uSTMatrixLoc, 1, false, stMatrix, 0) + + val mvp = FloatArray(16) + android.opengl.Matrix.setIdentityM(mvp, 0) + if (uMVPMatrixLoc != -1) GLES30.glUniformMatrix4fv(uMVPMatrixLoc, 1, false, mvp, 0) + + // 绑定 2D 纹理 + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId) + if (uCameraTextureLoc != -1) GLES30.glUniform1i(uCameraTextureLoc, 0) + + // 绘制 + if (aPositionLoc != -1) { + GLES30.glEnableVertexAttribArray(aPositionLoc) + GLES30.glVertexAttribPointer(aPositionLoc, 2, GLES30.GL_FLOAT, false, 0, vertexBuffer) + } + if (aTexCoordLoc != -1) { + GLES30.glEnableVertexAttribArray(aTexCoordLoc) + GLES30.glVertexAttribPointer(aTexCoordLoc, 2, GLES30.GL_FLOAT, false, 0, texCoordBuffer) + } + + GLES30.glDrawElements(GLES30.GL_TRIANGLES, 6, GLES30.GL_UNSIGNED_SHORT, indexBuffer) + + if (aPositionLoc != -1) GLES30.glDisableVertexAttribArray(aPositionLoc) + if (aTexCoordLoc != -1) GLES30.glDisableVertexAttribArray(aTexCoordLoc) + + EGLExt.eglPresentationTimeANDROID(eglDisplay, eglSurface, timestampUs * 1000) + EGL14.eglSwapBuffers(eglDisplay, eglSurface) + + EGL14.eglMakeCurrent(oldDisplay, oldDrawSurface, oldReadSurface, oldContext) + } + + fun release() { + if (eglDisplay != EGL14.EGL_NO_DISPLAY) { + EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT) + EGL14.eglDestroySurface(eglDisplay, eglSurface) + EGL14.eglDestroyContext(eglDisplay, eglContext) + EGL14.eglTerminate(eglDisplay) + } + shaderProgram = 0 + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/livephoto/LivePhotoRecorder.kt b/app/src/main/java/com/hinnka/mycamera/livephoto/LivePhotoRecorder.kt new file mode 100644 index 00000000..933a9daf --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/livephoto/LivePhotoRecorder.kt @@ -0,0 +1,339 @@ +package com.hinnka.mycamera.livephoto + +import android.content.Context +import android.media.MediaCodec +import android.media.MediaCodecInfo +import android.media.MediaFormat +import android.media.MediaMuxer +import android.opengl.* +import android.view.Surface +import com.hinnka.mycamera.lut.LutConfig +import com.hinnka.mycamera.model.ColorRecipeParams +import com.hinnka.mycamera.utils.PLog +import kotlinx.coroutines.* +import java.io.File +import java.nio.ByteBuffer +import java.util.* +import java.util.concurrent.ConcurrentLinkedDeque +import java.util.concurrent.Executors + +/** + * Live Photo 录制管理器 (重构版 - 解决 OOM) + * + * 采用“实时编码+样本缓冲”方案: + * 1. 持续将预览帧发送到硬件编码器 (MediaCodec)。 + * 2. 缓冲编码后的压缩数据 (H.264 Samples) 而非原始像素。 + * 3. 内存占用从数百 MB 降低到约 2-5 MB。 + */ +class LivePhotoRecorder( + private val context: Context, + private val bufferDurationMs: Long = 1500L, + private val postCaptureDurationMs: Long = 1500L, + private val frameRateHz: Int = 30 +) { + companion object { + private const val TAG = "LivePhotoRecorder" + private const val MIME_TYPE = MediaFormat.MIMETYPE_VIDEO_AVC + private const val BITRATE = 8_000_000 + private const val I_FRAME_INTERVAL = 1 + } + + // 核心组件 + // 缓冲区大小需要覆盖 预录制(bufferDuration) + 后录制(postCaptureDuration) + private val circularRecorder = CircularVideoRecorder(bufferDurationMs + postCaptureDurationMs) + + @Volatile + private var encoder: MediaCodec? = null + private var inputSurface: Surface? = null + + @Volatile + private var encoderFormat: MediaFormat? = null + + // 渲染组件 (负责将纹理绘制到编码器 Surface) + private var lutRenderer: HardwareLutVideoRenderer? = null + + // 状态控制 + @Volatile + private var isRunning = false + private var isCapturing = false + private var snapshotTimestampUs: Long = 0 + + private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob()) + private var drainJob: Job? = null + private val renderDispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher() + + private var lastFrameTimestampUs: Long = 0 + + /** + * 更新实时编码器的配置(如 LUT 或色彩配方) + */ + fun updateConfig(lutConfig: LutConfig?, params: ColorRecipeParams?) { + lutRenderer?.updateConfig(lutConfig, params) + } + + /** + * 开始录制 (当实况照片模式开启时调用) + */ + fun startRecording() { + if (isRunning) return + circularRecorder.startRecording() + isRunning = true + lastFrameTimestampUs = 0 + PLog.d(TAG, "Live Photo recording prepared") + } + + /** + * 停止录制 + */ + fun stopRecording() { + isRunning = false + drainJob?.cancel() + release() + PLog.d(TAG, "Live Photo background encoder stopped") + } + + /** + * 处理预览帧 (GL 线程调用) + */ + fun onPreviewFrame( + textureId: Int, + transformMatrix: FloatArray, + width: Int, + height: Int, + timestampNs: Long, + lutConfig: LutConfig?, + params: ColorRecipeParams?, + sharedContext: EGLContext + ) { + if (!isRunning) return + + lastFrameTimestampUs = timestampNs / 1000 + + val matrix = transformMatrix.clone() + scope.launch(renderDispatcher) { + // 延迟初始化编码器 (当收到第一帧时) + if (encoder == null) { + initEncoder(width, height, lutConfig, params, sharedContext) + } + + lutRenderer?.let { renderer -> + //PLog.v(TAG, "Rendering frame at ${timestampNs / 1000}") + // renderer.updateConfig(lutConfig, params) // No longer needed + renderer.renderFrame(textureId, matrix, timestampNs / 1000) + } + } + } + + private fun initEncoder( + width: Int, + height: Int, + lutConfig: LutConfig?, + params: ColorRecipeParams?, + sharedContext: EGLContext + ) { + try { + // 限制分辨率 + val maxDim = 1280 + var w = width + var h = height + if (w > maxDim || h > maxDim) { + if (w > h) { + h = (h * maxDim.toFloat() / w).toInt() + w = maxDim + } else { + w = (w * maxDim.toFloat() / h).toInt() + h = maxDim + } + } + + // Ensure even dimensions + if (w % 2 != 0) w-- + if (h % 2 != 0) h-- + + val format = MediaFormat.createVideoFormat(MIME_TYPE, w, h).apply { + setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface) + setInteger(MediaFormat.KEY_BIT_RATE, BITRATE) + setInteger(MediaFormat.KEY_FRAME_RATE, frameRateHz) + setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, I_FRAME_INTERVAL) + } + + encoder = MediaCodec.createEncoderByType(MIME_TYPE).apply { + configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) + inputSurface = createInputSurface() + start() + } + + lutRenderer = HardwareLutVideoRenderer(w, h, lutConfig, params).apply { + initialize(inputSurface!!, sharedContext) + } + + startDraining() + PLog.d(TAG, "Encoder initialized: ${w}x${h}") + } catch (e: Exception) { + PLog.e(TAG, "Failed to init encoder", e) + } + } + + /** + * 触发快照 (拍照时调用) + */ + fun snapshot(): List { + if (!isRunning) return emptyList() + + // 使用最近一帧的时间戳作为基准,避免时钟源不一致问题 + snapshotTimestampUs = lastFrameTimestampUs + if (snapshotTimestampUs == 0L) { + snapshotTimestampUs = System.nanoTime() / 1000 + } + + isCapturing = true + PLog.d(TAG, "Snapshot triggered at $snapshotTimestampUs") + return circularRecorder.snapshot() + } + + /** + * 完成并生成视频 (拍照后延迟调用) + */ + fun recordVideo( + lutConfig: LutConfig?, + params: ColorRecipeParams?, + onCaptured: (File, Long) -> Unit + ) { + // 由于是持续编码,lutConfig 和 params 已经在预览渲染时应用了 + scope.launch { + try { + // 等待后半段录制 + delay(postCaptureDurationMs) + + val currentSamples = circularRecorder.snapshot() + + // 筛选时间范围:[拍照前 bufferDurationMs, 拍照后 postCaptureDurationMs] + val startTimeUs = snapshotTimestampUs - bufferDurationMs * 1000 + val endTimeUs = snapshotTimestampUs + postCaptureDurationMs * 1000 + + PLog.d(TAG, "Filtering samples: snapshot=$snapshotTimestampUs, range=[$startTimeUs, $endTimeUs]") + + val targetSamples = currentSamples.filter { + it.info.presentationTimeUs in startTimeUs..endTimeUs + } + + PLog.d(TAG, "Found ${targetSamples.size} samples out of ${currentSamples.size} total") + if (currentSamples.isNotEmpty()) { + val first = currentSamples.first().info.presentationTimeUs + val last = currentSamples.last().info.presentationTimeUs + PLog.d(TAG, "Available range: [$first, $last]") + } + + if (targetSamples.isEmpty() || encoderFormat == null) { + PLog.e(TAG, "No samples or format to mux") + isCapturing = false + return@launch + } + + // 寻找第一个关键帧作为起点 + val firstSyncIdx = targetSamples.indexOfFirst { + (it.info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0 + } + + if (firstSyncIdx == -1) { + PLog.e(TAG, "No keyframe found in samples") + isCapturing = false + return@launch + } + + val muxSamples = targetSamples.subList(firstSyncIdx, targetSamples.size) + val videoFile = File(context.cacheDir, "livephoto_${System.currentTimeMillis()}.mp4") + + // 封装 MP4 + muxVideo(videoFile, muxSamples) + + // 计算拍照时刻在视频中的相对时间戳 + val startTs = muxSamples.first().info.presentationTimeUs + val presentationTimestampUs = snapshotTimestampUs - startTs + + onCaptured(videoFile, presentationTimestampUs) + + } catch (e: Exception) { + PLog.e(TAG, "Failed to finish Live Photo capture", e) + } finally { + isCapturing = false + } + } + } + + private fun startDraining() { + drainJob = scope.launch { + val bufferInfo = MediaCodec.BufferInfo() + while (isRunning) { + try { + val encoderRef = encoder ?: break + val outputBufferIndex = try { + encoderRef.dequeueOutputBuffer(bufferInfo, 10_000L) + } catch (e: IllegalStateException) { + break + } + + if (outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { + encoderFormat = encoderRef.outputFormat + PLog.d(TAG, "Encoder format changed: $encoderFormat") + } else if (outputBufferIndex == MediaCodec.INFO_TRY_AGAIN_LATER) { + //PLog.v(TAG, "Encoder dequeue timeout") + } else if (outputBufferIndex >= 0) { + val outputBuffer = encoderRef.getOutputBuffer(outputBufferIndex) + if (outputBuffer != null && bufferInfo.size > 0) { + circularRecorder.addSample(outputBuffer, bufferInfo) + } + encoderRef.releaseOutputBuffer(outputBufferIndex, false) + } + } catch (e: Exception) { + PLog.e(TAG, "Error draining encoder", e) + break + } + } + } + } + + private fun muxVideo(outputFile: File, samples: List) { + val muxer = MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4) + val trackIndex = muxer.addTrack(encoderFormat!!) + muxer.start() + + val baseTimeUs = samples.first().info.presentationTimeUs + samples.forEach { sample -> + val info = MediaCodec.BufferInfo() + info.set(0, sample.info.size, sample.info.presentationTimeUs - baseTimeUs, sample.info.flags) + val buffer = ByteBuffer.wrap(sample.data) + muxer.writeSampleData(trackIndex, buffer, info) + } + + muxer.stop() + muxer.release() + PLog.d(TAG, "Muxed ${samples.size} samples to ${outputFile.name}") + } + + fun release() { + isRunning = false + isCapturing = false + drainJob?.cancel() + + scope.launch(renderDispatcher) { + encoder?.let { + try { + it.stop(); it.release() + } catch (e: Exception) { + } + } + encoder = null + inputSurface = null + + lutRenderer?.release() + lutRenderer = null + + circularRecorder.release() + } + } + + // 简单透出状态 + fun isRecording(): Boolean = isRunning + fun isCapturing(): Boolean = isCapturing +} diff --git a/app/src/main/java/com/hinnka/mycamera/livephoto/MotionPhotoWriter.kt b/app/src/main/java/com/hinnka/mycamera/livephoto/MotionPhotoWriter.kt new file mode 100644 index 00000000..2d15b731 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/livephoto/MotionPhotoWriter.kt @@ -0,0 +1,473 @@ +package com.hinnka.mycamera.livephoto + +import com.hinnka.mycamera.utils.PLog +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.RandomAccessFile +import java.nio.charset.StandardCharsets + +/** + * Motion Photo 文件合成器 + * + * 将 JPEG 静态图片和 MP4 视频合成为符合 Android Motion Photo 1.0 规范的文件。 + * + * 文件结构: + * ``` + * +-------------------+ + * | JPEG 主图像 | (带 XMP 元数据) + * +-------------------+ + * | MP4 视频 | (紧随其后) + * +-------------------+ + * ``` + * + * 规范参考: https://developer.android.com/media/platform/motion-photo-format + */ +object MotionPhotoWriter { + private const val TAG = "MotionPhotoWriter" + + // JPEG 标记 + private const val JPEG_SOI = 0xFFD8 // Start of Image + private const val JPEG_EOI = 0xFFD9 // End of Image + private const val JPEG_APP1 = 0xFFE1 // APP1 (EXIF/XMP) + private const val JPEG_SOS = 0xFFDA // Start of Scan + + // XMP 命名空间 + private const val XMP_NS_X = "adobe:ns:meta/" + private const val XMP_NS_RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" + private const val XMP_NS_CAMERA = "http://ns.google.com/photos/1.0/camera/" + private const val XMP_NS_CAMERA_XIAOMI = "http://ns.xiaomi.com/photos/1.0/camera/" + private const val XMP_NS_CAMERA_OP = "http://ns.oplus.com/photos/1.0/camera/" + private const val XMP_NS_CONTAINER = "http://ns.google.com/photos/1.0/container/" + private const val XMP_NS_ITEM = "http://ns.google.com/photos/1.0/container/item/" + + /** + * 合成 Motion Photo 文件 + * + * @param jpegPath 静态 JPEG 图片路径 + * @param videoPath MP4 视频路径 + * @param outputPath 输出 Motion Photo 路径 + * @param presentationTimestampUs 静态帧对应的视频时间戳 (微秒) + * @return 是否成功 + */ + fun write( + jpegPath: String, + videoPath: String, + outputPath: String, + presentationTimestampUs: Long + ): Boolean { + try { + val jpegFile = File(jpegPath) + val videoFile = File(videoPath) + + if (!jpegFile.exists()) { + PLog.e(TAG, "JPEG file not found: $jpegPath") + return false + } + if (!videoFile.exists()) { + PLog.e(TAG, "Video file not found: $videoPath") + return false + } + + val videoLength = videoFile.length() + + // 生成 Motion Photo XMP 元数据 + val xmpData = buildMotionPhotoXmp(videoLength, presentationTimestampUs) + + // 使用流式处理,避免大文件 OOM + FileOutputStream(outputPath).use { output -> + FileInputStream(jpegPath).use { jpegInput -> + // 1. 注入 XMP 并写入 JPEG 内容 + if (!injectXmpToStream(jpegInput, output, xmpData)) { + PLog.e(TAG, "Failed to inject XMP") + return false + } + } + + // 2. 追加 MP4 视频 + FileInputStream(videoPath).use { videoInput -> + val buffer = ByteArray(8192) + var bytesRead: Int + while (videoInput.read(buffer).also { bytesRead = it } != -1) { + output.write(buffer, 0, bytesRead) + } + } + } + + PLog.d(TAG, "Motion Photo created: $outputPath (Video: $videoLength)") + return true + + } catch (e: Exception) { + PLog.e(TAG, "Failed to write Motion Photo", e) + return false + } + } + + /** + * 将 XMP 元数据注入到 JPEG 流 (Robust Byte-level Scanner) + * + * 精确处理 JPEG 标记结构, + * 策略:将 XMP 插入到 Exif (APP1) 之后,或者如果不存在 Exif,则在 SOI 之后。 + * 尽量靠前插入,以兼容部分只扫描文件头部的解析器。 + */ + private fun injectXmpToStream(input: FileInputStream, output: FileOutputStream, xmpData: ByteArray): Boolean { + try { + // 使用 BufferedInputStream 以提高逐字节读取性能 + val bis = java.io.BufferedInputStream(input) + + // 1. 验证 SOI (FF D8) + val b1 = bis.read() + val b2 = bis.read() + if (b1 != 0xFF || b2 != 0xD8) { + PLog.e(TAG, "Invalid JPEG: missing SOI marker") + return false + } + output.write(b1) + output.write(b2) + + // 准备 XMP APP1 段数据 + val xmpNamespace = "http://ns.adobe.com/xap/1.0/\u0000" + val namespaceBytes = xmpNamespace.toByteArray(StandardCharsets.US_ASCII) + val segmentLength = 2 + namespaceBytes.size + xmpData.size + var xmpInserted = false + + while (true) { + // 查找下一个标记开始 (0xFF) + var markerByte = bis.read() + while (markerByte != 0xFF && markerByte != -1) { + output.write(markerByte) + markerByte = bis.read() + } + if (markerByte == -1) break // EOF + + // 读取标记类型字节 + var typeByte = bis.read() + if (typeByte == -1) { + output.write(markerByte) // 写入最后的 FF + break + } + + // 处理填充字节 (FF FF ... FF XX) + while (typeByte == 0xFF) { + output.write(markerByte) // 写入前一个 FF + markerByte = typeByte + typeByte = bis.read() + } + + val marker = typeByte + + // 决策:在哪里插入 XMP? + // 如果还未插入,且当前标记 不是 APP0 (JFIF) 且 不是 APP1 (Exif),则在此插入 + // 注意:Exif 也是 APP1,通常以 "Exif\0\0" 开头。这里简化处理,假设第一个 APP1 是 Exif。 + // 如果遇到 APP0 或 APP1,先写入它们,推迟插入。 + // 如果遇到其他任何标记(APP2-15, DQT, SOF, SOS等),立即插入 XMP。 + + val isApp0 = marker == 0xE0 + val isApp1 = marker == 0xE1 + + if (!xmpInserted && !isApp0 && !isApp1) { + // --- 在此插入 XMP --- + output.write(0xFF) + output.write(0xE1) + output.write((segmentLength shr 8) and 0xFF) + output.write(segmentLength and 0xFF) + output.write(namespaceBytes) + output.write(xmpData) + xmpInserted = true + } + + if (marker == 0xDA) { // SOS (Start of Scan) - 0xDA + // 如果到 SOS 还没插入(例如只有 APP0/APP1),强制插入 + if (!xmpInserted) { + output.write(0xFF) + output.write(0xE1) + output.write((segmentLength shr 8) and 0xFF) + output.write(segmentLength and 0xFF) + output.write(namespaceBytes) + output.write(xmpData) + xmpInserted = true + } + + // 写入原本的 SOS 标记 + output.write(markerByte) // FF + output.write(typeByte) // DA + + // 复制剩余所有数据 + val buffer = ByteArray(8192) + var len: Int + while (bis.read(buffer).also { len = it } != -1) { + output.write(buffer, 0, len) + } + return true + } + + // 写入当前标记 + output.write(markerByte) + output.write(typeByte) + + // 处理标记负载 + val isStandalone = marker == 0x01 || (marker in 0xD0..0xD9) + if (!isStandalone) { + val lenHi = bis.read() + val lenLo = bis.read() + if (lenHi == -1 || lenLo == -1) return false + + output.write(lenHi) + output.write(lenLo) + + val length = ((lenHi and 0xFF) shl 8) or (lenLo and 0xFF) + val bodyLen = length - 2 + + if (bodyLen > 0) { + var remaining = bodyLen + val buffer = ByteArray(minOf(4096, remaining)) + while (remaining > 0) { + val toRead = minOf(buffer.size, remaining) + val read = bis.read(buffer, 0, toRead) + if (read == -1) return false + output.write(buffer, 0, read) + remaining -= read + } + } + } + } + + PLog.e(TAG, "SOS marker not found in JPEG stream") + return false + } catch (e: Exception) { + PLog.e(TAG, "Error injecting XMP", e) + return false + } + } + + /** + * 构建 Motion Photo XMP 元数据 + */ + private fun buildMotionPhotoXmp(videoLength: Long, presentationTimestampUs: Long): ByteArray { + val xmp = buildString { + // "Dual-Metadata" Strategy: + // Reverting to Attribute-based syntax for Container Items which is standard for Google Photos. + + append("") + append("") + append("") + append("") + + // Container Directory + append("") + append("") + + // Item 1: Primary Image + append("") + append("") + append("") + + // Item 2: Motion Photo Video + append("") + append("") + append("") + + append("") + append("") + + append("") + append("") + append("") + + // Add padding (Standard is usually whitespace in the packet wrapper) + for (i in 0..2000) { + append(" ") + } + + append("") + } + + return xmp.toByteArray(StandardCharsets.UTF_8) + } + + /** + * 将 XMP 元数据注入到 JPEG 文件 + * + * 在 JPEG 的 APP1 段后插入新的 APP1 段包含 Motion Photo XMP + */ + private fun injectXmpToJpeg(jpegData: ByteArray, xmpData: ByteArray): ByteArray? { + if (jpegData.size < 4) return null + + // 验证 JPEG SOI + if ((jpegData[0].toInt() and 0xFF) != 0xFF || (jpegData[1].toInt() and 0xFF) != 0xD8) { + PLog.e(TAG, "Invalid JPEG: missing SOI marker") + return null + } + + // 构建 APP1 段 + // 格式: FF E1 [length 2 bytes] "http://ns.adobe.com/xap/1.0/\0" [xmp data] + val xmpNamespace = "http://ns.adobe.com/xap/1.0/\u0000" + val namespaceBytes = xmpNamespace.toByteArray(StandardCharsets.US_ASCII) + val segmentLength = 2 + namespaceBytes.size + xmpData.size + + if (segmentLength > 65535) { + PLog.e(TAG, "XMP data too large for APP1 segment") + return null + } + + val app1Segment = ByteArray(2 + 2 + namespaceBytes.size + xmpData.size) + app1Segment[0] = 0xFF.toByte() + app1Segment[1] = 0xE1.toByte() + app1Segment[2] = ((segmentLength shr 8) and 0xFF).toByte() + app1Segment[3] = (segmentLength and 0xFF).toByte() + System.arraycopy(namespaceBytes, 0, app1Segment, 4, namespaceBytes.size) + System.arraycopy(xmpData, 0, app1Segment, 4 + namespaceBytes.size, xmpData.size) + + // 找到插入位置 (SOI 之后) + var insertPos = 2 // 跳过 SOI + + // 跳过已存在的 APP0-APP15 和其他段,直到找到合适的插入点 + while (insertPos < jpegData.size - 1) { + val marker1 = jpegData[insertPos].toInt() and 0xFF + val marker2 = jpegData[insertPos + 1].toInt() and 0xFF + + if (marker1 != 0xFF) { + // 不是标记,可能已经进入图像数据 + break + } + + val marker = (marker1 shl 8) or marker2 + + // 如果遇到 SOS (Start of Scan),在它之前插入 + if (marker == JPEG_SOS) { + break + } + + // 跳过这个段 + if (marker in 0xFFE0..0xFFEF || marker in 0xFFC0..0xFFCF || marker == 0xFFFE) { + if (insertPos + 3 >= jpegData.size) break + val length = ((jpegData[insertPos + 2].toInt() and 0xFF) shl 8) or + (jpegData[insertPos + 3].toInt() and 0xFF) + insertPos += 2 + length + } else { + // 其他标记,停止 + break + } + } + + // 构建输出 + val result = ByteArray(jpegData.size + app1Segment.size) + System.arraycopy(jpegData, 0, result, 0, insertPos) + System.arraycopy(app1Segment, 0, result, insertPos, app1Segment.size) + System.arraycopy(jpegData, insertPos, result, insertPos + app1Segment.size, jpegData.size - insertPos) + + return result + } + + /** + * 从 Motion Photo 文件的 XMP 中获取视频长度 + */ + private fun getVideoLength(motionPhotoPath: String): Long { + try { + val jpegData = File(motionPhotoPath).readBytes() + var pos = 2 + while (pos < jpegData.size - 1) { + val marker = ((jpegData[pos].toInt() and 0xFF) shl 8) or (jpegData[pos + 1].toInt() and 0xFF) + if (marker == JPEG_SOS) break + if (marker == JPEG_APP1) { + val length = ((jpegData[pos + 2].toInt() and 0xFF) shl 8) or (jpegData[pos + 3].toInt() and 0xFF) + val segmentData = jpegData.copyOfRange(pos + 4, minOf(pos + 4 + length - 2, jpegData.size)) + val segmentString = String(segmentData, StandardCharsets.UTF_8) + if (segmentString.contains("MicroVideoOffset")) { + val regex = """MicroVideoOffset="(\d+)"""".toRegex() + val match = regex.find(segmentString) + if (match != null) return match.groupValues[1].toLongOrNull() ?: 0L + } + pos += 2 + length + } else { + val length = ((jpegData[pos + 2].toInt() and 0xFF) shl 8) or (jpegData[pos + 3].toInt() and 0xFF) + pos += 2 + length + } + } + } catch (e: Exception) { + PLog.e(TAG, "Failed to parse XMP for offset", e) + } + return 0L + } + + /** + * 检查文件是否是 Motion Photo + */ + fun isMotionPhoto(filePath: String): Boolean { + try { + val jpegData = File(filePath).readBytes() + var pos = 2 + while (pos < jpegData.size - 1) { + val marker = ((jpegData[pos].toInt() and 0xFF) shl 8) or (jpegData[pos + 1].toInt() and 0xFF) + if (marker == JPEG_SOS) break + if (marker == JPEG_APP1) { + val length = ((jpegData[pos + 2].toInt() and 0xFF) shl 8) or (jpegData[pos + 3].toInt() and 0xFF) + val segmentData = jpegData.copyOfRange(pos + 4, minOf(pos + 4 + length - 2, jpegData.size)) + val segmentString = String(segmentData, StandardCharsets.UTF_8) + if (segmentString.contains("MicroVideo=\"1\"")) return true + pos += 2 + length + } else { + val length = ((jpegData[pos + 2].toInt() and 0xFF) shl 8) or (jpegData[pos + 3].toInt() and 0xFF) + pos += 2 + length + } + } + } catch (e: Exception) { + PLog.e(TAG, "Failed to check Motion Photo", e) + } + return false + } + + /** + * 获取 Motion Photo 的视频时间戳 + */ + fun getPresentationTimestampUs(filePath: String): Long { + try { + val jpegData = File(filePath).readBytes() + var pos = 2 + while (pos < jpegData.size - 1) { + val marker = ((jpegData[pos].toInt() and 0xFF) shl 8) or (jpegData[pos + 1].toInt() and 0xFF) + if (marker == JPEG_SOS) break + if (marker == JPEG_APP1) { + val length = ((jpegData[pos + 2].toInt() and 0xFF) shl 8) or (jpegData[pos + 3].toInt() and 0xFF) + val segmentData = jpegData.copyOfRange(pos + 4, minOf(pos + 4 + length - 2, jpegData.size)) + val segmentString = String(segmentData, StandardCharsets.UTF_8) + if (segmentString.contains("MicroVideoPresentationTimestampUs")) { + val regex = """MicroVideoPresentationTimestampUs="(\d+)"""".toRegex() + val match = regex.find(segmentString) + if (match != null) return match.groupValues[1].toLongOrNull() ?: -1L + } + pos += 2 + length + } else { + val length = ((jpegData[pos + 2].toInt() and 0xFF) shl 8) or (jpegData[pos + 3].toInt() and 0xFF) + pos += 2 + length + } + } + } catch (e: Exception) { + PLog.e(TAG, "Failed to get timestamp", e) + } + return -1L + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt index ca3c2358..1fbde59c 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt @@ -2,11 +2,15 @@ package com.hinnka.mycamera.lut import android.graphics.Bitmap import android.graphics.SurfaceTexture +import android.opengl.EGL14 import android.opengl.GLES11Ext import android.opengl.GLES30 import android.opengl.GLSurfaceView import android.opengl.Matrix import android.util.Log +import android.view.Surface +import com.hinnka.mycamera.livephoto.LivePhotoRecorder +import com.hinnka.mycamera.lut.LutConfig import com.hinnka.mycamera.utils.PLog import java.nio.ByteBuffer import java.nio.ByteOrder @@ -47,6 +51,18 @@ class LutRenderer : GLSurfaceView.Renderer { private var indexBufferId: Int = 0 private var pboId: Int = 0 + // FBO 相关 + private var fboId: Int = 0 + private var fboTextureId: Int = 0 + + // Copy Shader (FBO -> Screen) + private var copyProgramId: Int = 0 + private var uCopyTextureLoc: Int = 0 + private var uCopyMVPMatrixLoc: Int = 0 + private var uCopySTMatrixLoc: Int = 0 + private var aCopyPositionLoc: Int = 0 + private var aCopyTexCoordLoc: Int = 0 + // Uniform 位置 private var uMVPMatrixLocation: Int = 0 private var uSTMatrixLocation: Int = 0 @@ -159,6 +175,9 @@ class LutRenderer : GLSurfaceView.Renderer { var onRequestRender: (() -> Unit)? = null var onPreviewFrameCaptured: ((Bitmap) -> Unit)? = null + // Live Photo 录制器 + var livePhotoRecorder: LivePhotoRecorder? = null + // 预览帧捕获标志 private var shouldCapturePreview = false private val captureSize = 128 // 预览图尺寸 @@ -209,6 +228,9 @@ class LutRenderer : GLSurfaceView.Renderer { // 通知调用者 SurfaceTexture 已准备好 surfaceTexture?.let { onSurfaceTextureAvailable?.invoke(it) } + // 通知调用者 SurfaceTexture 已准备好 + surfaceTexture?.let { onSurfaceTextureAvailable?.invoke(it) } + GlUtils.checkGlError("onSurfaceCreated") } @@ -223,12 +245,57 @@ class LutRenderer : GLSurfaceView.Renderer { GLES30.glViewport(0, 0, width, height) + // 初始化 FBO + initFbo(width, height) + // 更新 MVP 矩阵以处理 center crop updateMVPMatrix() GlUtils.checkGlError("onSurfaceChanged") } + private fun initFbo(width: Int, height: Int) { + if (fboId != 0) { + GLES30.glDeleteFramebuffers(1, intArrayOf(fboId), 0) + fboId = 0 + } + if (fboTextureId != 0) { + GLES30.glDeleteTextures(1, intArrayOf(fboTextureId), 0) + fboTextureId = 0 + } + + val ids = IntArray(1) + GLES30.glGenFramebuffers(1, ids, 0) + fboId = ids[0] + + GLES30.glGenTextures(1, ids, 0) + fboTextureId = ids[0] + + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, fboTextureId) + GLES30.glTexImage2D( + GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, width, height, + 0, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null + ) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) + + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fboId) + GLES30.glFramebufferTexture2D( + GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, + GLES30.GL_TEXTURE_2D, fboTextureId, 0 + ) + + val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) + if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) { + PLog.e(TAG, "FBO init failed: $status") + } + + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + } + /** * 绘制帧 */ @@ -242,6 +309,87 @@ class LutRenderer : GLSurfaceView.Renderer { } } + if (fboId != 0 && fboTextureId != 0) { + // 1. 渲染到 FBO (OES -> FBO, 应用 LUT) + drawInternal(fboId, viewportWidth, viewportHeight) + + // FBO 纹理已经是正向的,所以传给 Recorder 时使用 Identity 矩阵 + val identity = FloatArray(16) + Matrix.setIdentityM(identity, 0) + + // 2. 为 Live Photo 提供预览帧 (使用 FBO 纹理, GL_TEXTURE_2D) + livePhotoRecorder?.onPreviewFrame( + textureId = fboTextureId, + transformMatrix = identity, + width = viewportWidth, + height = viewportHeight, + timestampNs = surfaceTexture?.timestamp ?: 0L, + lutConfig = currentLutConfig, + params = getCurrentRecipeParams(), + sharedContext = EGL14.eglGetCurrentContext() + ) + + // 3. 将 FBO 绘制到屏幕 + drawFboToScreen(0, viewportWidth, viewportHeight) + } else { + // FBO 未就绪,直接渲染到屏幕 (Fallback) + drawInternal(0, viewportWidth, viewportHeight) + } + } + + /** + * 将 FBO 纹理绘制到屏幕 (Copy Shader) + */ + private fun drawFboToScreen(fboId: Int, width: Int, height: Int) { + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fboId) + GLES30.glViewport(0, 0, width, height) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + + GLES30.glUseProgram(copyProgramId) + + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, fboTextureId) + GLES30.glUniform1i(uCopyTextureLoc, 0) + + // FBO 纹理已经是正向的 (经过 stMatrix/MVP 处理后),所以这里可能不需要再变换 + // 或者需要 Identity + val identity = FloatArray(16) + Matrix.setIdentityM(identity, 0) + GLES30.glUniformMatrix4fv(uCopyMVPMatrixLoc, 1, false, identity, 0) + + // stMatrix 也设为 Identity,因为 FBO 纹理坐标是标准的 + GLES30.glUniformMatrix4fv(uCopySTMatrixLoc, 1, false, identity, 0) + + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, vertexBufferId) + GLES30.glEnableVertexAttribArray(aCopyPositionLoc) + GLES30.glVertexAttribPointer(aCopyPositionLoc, POSITION_COMPONENT_COUNT, GLES30.GL_FLOAT, false, 0, 0) + + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, texCoordBufferId) + GLES30.glEnableVertexAttribArray(aCopyTexCoordLoc) + GLES30.glVertexAttribPointer(aCopyTexCoordLoc, TEXTURE_COORD_COMPONENT_COUNT, GLES30.GL_FLOAT, false, 0, 0) + + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, indexBufferId) + GLES30.glDrawElements(GLES30.GL_TRIANGLES, Shaders.DRAW_ORDER.size, GLES30.GL_UNSIGNED_SHORT, 0) + + GLES30.glDisableVertexAttribArray(aCopyPositionLoc) + GLES30.glDisableVertexAttribArray(aCopyTexCoordLoc) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0) + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, 0) + + // 捕获预览帧 (如果需要) + if (fboId == 0 && shouldCapturePreview) { + shouldCapturePreview = false + capturePreviewFrameInternal() + } + } + + /** + * 内部绘图逻辑,支持渲染到 FBO 或屏幕 + */ + private fun drawInternal(fboId: Int, width: Int, height: Int) { + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fboId) + GLES30.glViewport(0, 0, width, height) + // 清屏 GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) @@ -332,7 +480,7 @@ class LutRenderer : GLSurfaceView.Renderer { GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, 0) // 捕获预览帧(如果需要) - if (shouldCapturePreview) { + if (fboId == 0 && shouldCapturePreview) { shouldCapturePreview = false capturePreviewFrameInternal() } @@ -385,12 +533,29 @@ class LutRenderer : GLSurfaceView.Renderer { uShadowsLocation = GLES30.glGetUniformLocation(programId, "uShadows") uFilmGrainLocation = GLES30.glGetUniformLocation(programId, "uFilmGrain") uVignetteLocation = GLES30.glGetUniformLocation(programId, "uVignette") + // ... existing initShaderProgram code ... uBleachBypassLocation = GLES30.glGetUniformLocation(programId, "uBleachBypass") - // 获取 Attribute 位置 + // Attribute 位置 aPositionLocation = GLES30.glGetAttribLocation(programId, "aPosition") aTexCoordLocation = GLES30.glGetAttribLocation(programId, "aTexCoord") + // === 初始化 Copy Shader (用于 FBO 上屏) === + val copyVs = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, Shaders.VERTEX_SHADER) + val copyFs = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, Shaders.FRAGMENT_SHADER_COPY_2D) + copyProgramId = GlUtils.linkProgram(copyVs, copyFs) + GLES30.glDeleteShader(copyVs) + GLES30.glDeleteShader(copyFs) + + if (copyProgramId == 0) { + PLog.e(TAG, "Failed to link copy program") + } else { + uCopyTextureLoc = GLES30.glGetUniformLocation(copyProgramId, "uCameraTexture") + uCopyMVPMatrixLoc = GLES30.glGetUniformLocation(copyProgramId, "uMVPMatrix") + uCopySTMatrixLoc = GLES30.glGetUniformLocation(copyProgramId, "uSTMatrix") + aCopyPositionLoc = GLES30.glGetAttribLocation(copyProgramId, "aPosition") + aCopyTexCoordLoc = GLES30.glGetAttribLocation(copyProgramId, "aTexCoord") + } // PLog.d(TAG, "Shader program created: $programId") } @@ -611,7 +776,7 @@ class LutRenderer : GLSurfaceView.Renderer { pixelSize, GLES30.GL_MAP_READ_BIT ) as? ByteBuffer - + if (mappedBuffer == null) { GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0) return @@ -695,4 +860,25 @@ class LutRenderer : GLSurfaceView.Renderer { surfaceReady = false pendingLutConfig = null } + + /** + * 获取当前色彩配方参数对象 + */ + private fun getCurrentRecipeParams(): com.hinnka.mycamera.model.ColorRecipeParams { + return com.hinnka.mycamera.model.ColorRecipeParams( + lutIntensity = lutIntensity, + exposure = exposure, + contrast = contrast, + saturation = saturation, + temperature = temperature, + tint = tint, + color = vibrance, + highlights = highlights, + shadows = shadows, + fade = fade, + filmGrain = filmGrain, + vignette = vignette, + bleachBypass = bleachBypass + ) + } } diff --git a/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt b/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt index f10be36f..eb2bb99f 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt @@ -4,7 +4,7 @@ package com.hinnka.mycamera.lut * GLSL 着色器源代码 */ object Shaders { - + /** * 顶点着色器 * @@ -38,7 +38,7 @@ object Shaders { vTexCoord = (uSTMatrix * vec4(aTexCoord, 0.0, 1.0)).xy; } """.trimIndent() - + /** * 片元着色器 - 带 3D LUT 支持 * @@ -98,7 +98,7 @@ object Shaders { fragColor = vec4(finalColor, originalColor.a); } """.trimIndent() - + /** * 简单的直通片元着色器(无 LUT) * @@ -120,6 +120,24 @@ object Shaders { } """.trimIndent() + /** + * 片元着色器 - 2D 纹理复制 (支持 sampler2D) + * 用于从 FBO 纹理复制到屏幕或视频编码器 + */ + val FRAGMENT_SHADER_COPY_2D = """ + #version 300 es + precision mediump float; + + in vec2 vTexCoord; + out vec4 fragColor; + + uniform sampler2D uCameraTexture; + + void main() { + fragColor = texture(uCameraTexture, vTexCoord); + } + """.trimIndent() + /** * 片元着色器 - 带色彩配方和 3D LUT 支持 * @@ -131,217 +149,218 @@ object Shaders { * - 避免 HSL 转换,使用基于 Luma 的快速饱和度算法 */ val FRAGMENT_SHADER_COLOR_RECIPE = """ - #version 300 es - #extension GL_OES_EGL_image_external_essl3 : require + #version 300 es + #extension GL_OES_EGL_image_external_essl3 : require - precision highp float; + precision highp float; - // 从顶点着色器接收的纹理坐标 - in vec2 vTexCoord; + // 从顶点着色器接收的纹理坐标 + in vec2 vTexCoord; - // 输出颜色 - out vec4 fragColor; + // 输出颜色 + out vec4 fragColor; - // 相机 OES 纹理 - uniform samplerExternalOES uCameraTexture; + // 相机 OES 纹理 + uniform samplerExternalOES uCameraTexture; - // 3D LUT 纹理 - uniform mediump sampler3D uLutTexture; + // 3D LUT 纹理 + uniform mediump sampler3D uLutTexture; - // LUT 控制 - uniform float uLutSize; - uniform float uLutIntensity; - uniform bool uLutEnabled; + // LUT 控制 + uniform float uLutSize; + uniform float uLutIntensity; + uniform bool uLutEnabled; - // 色彩配方控制 - uniform bool uColorRecipeEnabled; + // 色彩配方控制 + uniform bool uColorRecipeEnabled; - // 色彩配方参数(阶段1:核心3参数) - uniform float uExposure; // -2.0 ~ +2.0 (EV) - uniform float uContrast; // 0.5 ~ 1.5 - uniform float uSaturation; // 0.0 ~ 2.0 + // 色彩配方参数(阶段1:核心3参数) + uniform float uExposure; // -2.0 ~ +2.0 (EV) + uniform float uContrast; // 0.5 ~ 1.5 + uniform float uSaturation; // 0.0 ~ 2.0 - // 色彩配方参数(阶段1:额外3参数) - uniform float uTemperature; // -1.0 ~ +1.0 (暖/冷色调) - uniform float uTint; // -1.0 ~ +1.0 (绿/品红偏移) - uniform float uFade; // 0.0 ~ 1.0 (褪色效果) - uniform float uVibrance; // 0.0 ~ 2.0 (蓝色增强 - vibrance) + // 色彩配方参数(阶段1:额外3参数) + uniform float uTemperature; // -1.0 ~ +1.0 (暖/冷色调) + uniform float uTint; // -1.0 ~ +1.0 (绿/品红偏移) + uniform float uFade; // 0.0 ~ 1.0 (褪色效果) + uniform float uVibrance; // 0.0 ~ 2.0 (蓝色增强 - vibrance) - // 色彩配方参数(阶段2:高级参数) - uniform float uHighlights; // -1.0 ~ +1.0 (高光调整) - uniform float uShadows; // -1.0 ~ +1.0 (阴影调整) + // 色彩配方参数(阶段2:高级参数) + uniform float uHighlights; // -1.0 ~ +1.0 (高光调整) + uniform float uShadows; // -1.0 ~ +1.0 (阴影调整) - // 色彩配方参数(阶段3:质感效果) - uniform float uFilmGrain; // 0.0 ~ 1.0 (颗粒强度) - uniform float uVignette; // -1.0 ~ +1.0 (晕影,负值暗角,正值亮角) - uniform float uBleachBypass; // 0.0 ~ 1.0 (留银冲洗强度) + // 色彩配方参数(阶段3:质感效果) + uniform float uFilmGrain; // 0.0 ~ 1.0 (颗粒强度) + uniform float uVignette; // -1.0 ~ +1.0 (晕影,负值暗角,正值亮角) + uniform float uBleachBypass; // 0.0 ~ 1.0 (留银冲洗强度) - void main() { - // 从相机纹理采样原始颜色 - vec4 color = texture(uCameraTexture, vTexCoord); - - // Early exit 优化:无任何调整时直接输出 - if (!uColorRecipeEnabled && !uLutEnabled) { - fragColor = color; - return; - } - - // === 色彩配方处理(按专业后期流程顺序) === - if (uColorRecipeEnabled) { - // 1. 曝光调整(线性空间,最先执行避免 clipping) - color.rgb *= pow(2.0, uExposure); - - // 2. 高光/阴影调整(分区调整,基于亮度 mask) - float luma = dot(color.rgb, vec3(0.299, 0.587, 0.114)); - float highlightMask = smoothstep(0.5, 1.0, luma); - float shadowMask = smoothstep(0.5, 0.0, luma); - float highlightFactor; - if (uHighlights > 0.0) { - highlightFactor = 1.0 + uHighlights * 0.7; - } else { - highlightFactor = 1.0 + uHighlights * 0.3; - } - color.rgb = mix(color.rgb, color.rgb * highlightFactor, highlightMask); - vec3 shadowTarget; - if (uShadows > 0.0) { - shadowTarget = mix(color.rgb, vec3(1.0) * luma, uShadows * 0.2) + (color.rgb * uShadows * 0.5); - } else { - shadowTarget = color.rgb * (1.0 + uShadows * 0.5); - } - color.rgb = mix(color.rgb, shadowTarget, shadowMask); - - // 3. 对比度(围绕中灰点调整) - color.rgb = (color.rgb - 0.5) * uContrast + 0.5; - - // 4. 白平衡调整(色温 + 色调) - // 色温:增加暖色调(偏红)或冷色调(偏蓝) - color.r += uTemperature * 0.1; - color.b -= uTemperature * 0.1; - // 色调:绿-品红偏移 - color.g += uTint * 0.05; - - // 5. 饱和度(基于 Luma 的快速算法,避免 HSL 转换) - float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114)); - color.rgb = mix(vec3(gray), color.rgb, uSaturation); - - // 6. 色彩增强(Vibrance - 选择性增强蓝色/红橙色) - float strength = uVibrance * 0.5; - // --- 6.1 蓝色增强 (深邃天空/水面) --- - float baseBlue = color.b - (color.r + color.g) * 0.5; - float blueMask = smoothstep(0.0, 0.2, baseBlue); - if (blueMask > 0.0) { - // 增加蓝色的纯度 (使用比例混合,避免绝对值减法产生噪点) - color.r = mix(color.r, color.r * 0.7, blueMask * strength); - color.g = mix(color.g, color.g * 0.7, blueMask * strength); - // 稍微压暗蓝色,制造胶片重感 (同样使用比例混合) - color.b = mix(color.b, color.b * 0.95, blueMask * strength); - // 使用 S 曲线增加蓝色区域的对比度/通透感 - vec3 sCurve = color.rgb * color.rgb * (3.0 - 2.0 * color.rgb); - color.rgb = mix(color.rgb, sCurve, blueMask * strength * 0.2); - } - // --- 6.2 暖色增强 (新增逻辑:红润肤色/日落) --- - // 去除浑浊的蓝色杂质,呈现奶油般质感的红/橙色 - // 算法:检测红色分量是否显著高于蓝色 (捕捉皮肤、夕阳、木头等) - float baseWarm = color.r - (color.g * 0.3 + color.b * 0.7); - float warmMask = smoothstep(0.05, 0.25, baseWarm); - if (warmMask > 0.0) { - // 6.2.1 "去脏":只在一定范围内应用,避免把鲜艳的红色变黑 - color.b = mix(color.b, color.b * 0.85, warmMask * strength); - // 6.2.2 密度调整 - color.g = mix(color.g, color.g * 0.95, warmMask * strength); - // 6.2.3 胶片感增强:使用非线性缩放而不是简单的乘法,保护亮度 - vec3 sCurve = color.rgb * color.rgb * (3.0 - 2.0 * color.rgb); - color.rgb = mix(color.rgb, sCurve, warmMask * strength * 0.25); - } - - // 7. 褪色效果(降低对比度 + 提升黑电平) - if (uFade > 0.0) { - float fadeAmount = uFade * 0.3; - color.rgb = mix(color.rgb, vec3(0.5), fadeAmount); - color.rgb += fadeAmount * 0.1; - } - - // 8. 留银冲洗(Bleach Bypass - 胶片银盐保留效果) - if (uBleachBypass > 0.0) { - // 保留部分银盐:降低饱和度 - float luma = dot(color.rgb, vec3(0.299, 0.587, 0.114)); - vec3 desaturated = mix(color.rgb, vec3(luma), 0.6); - - // 增强对比度 - desaturated = (desaturated - 0.5) * 1.3 + 0.5; - - // 色调偏移到冷色调(青绿色) - desaturated.r *= 0.95; - desaturated.g *= 1.02; - desaturated.b *= 1.05; - - // 根据强度混合 - color.rgb = mix(color.rgb, desaturated, uBleachBypass); - } - - // 9. 晕影(Vignette - 边缘光线衰减/增强) - if (abs(uVignette) > 0.0) { - // 计算从中心到边缘的距离 - vec2 center = vec2(0.5, 0.5); - float dist = distance(vTexCoord, center); - - // 使用 smoothstep 创建平滑过渡 - // 调整衰减曲线:从0.3到0.8的范围 - float vignetteMask = smoothstep(0.8, 0.3, dist); - - // 根据 uVignette 符号决定是暗角还是亮角 - if (uVignette < 0.0) { - // 暗角:边缘变暗(更强的效果:从0.01到1.0) - color.rgb *= mix(0.01, 1.0, vignetteMask) * abs(uVignette) + (1.0 + uVignette); - } else { - // 亮角:边缘变亮(增强效果) - color.rgb = mix(color.rgb, vec3(1.0), (1.0 - vignetteMask) * uVignette); - } - } - - // 10. 颗粒(Film Grain - 胶片颗粒感) - if (uFilmGrain > 0.0) { - // 使用纹理坐标生成伪随机噪声 - // 基于片段位置的简单哈希函数 - float noise = fract(sin(dot(vTexCoord * 1000.0, vec2(12.9898, 78.233))) * 43758.5453); - - // 将噪声从 [0,1] 映射到 [-1,1] - noise = (noise - 0.5) * 2.0; - - // 根据亮度自适应调整颗粒强度(高光和阴影更明显) - float luma = dot(color.rgb, vec3(0.299, 0.587, 0.114)); - float grainMask = 1.0 - abs(luma - 0.5) * 2.0; // 中间调弱,高光阴影强 - grainMask = grainMask * 0.5 + 0.5; // 调整到 [0.5, 1.0] 范围 - - // 应用颗粒(增强强度) - float grainStrength = uFilmGrain * 0.1 * grainMask; - color.rgb += noise * grainStrength; - } - - // Clamp 到合法范围 - color.rgb = clamp(color.rgb, 0.0, 1.0); - } - - // === LUT 处理(在色彩配方之后,保持 LUT 创作意图) === - if (uLutEnabled && uLutIntensity > 0.0) { - // 3D LUT 查找 - float scale = (uLutSize - 1.0) / uLutSize; - float offset = 1.0 / (2.0 * uLutSize); - - // 将 RGB 值映射到 LUT 纹理坐标 - vec3 lutCoord = color.rgb * scale + offset; - - // 从 3D LUT 纹理采样 - vec4 lutColor = texture(uLutTexture, lutCoord); - - // 根据强度混合色彩配方处理后的颜色和 LUT 颜色 - color.rgb = mix(color.rgb, lutColor.rgb, uLutIntensity); - } + void main() + { + // 从相机纹理采样原始颜色 + vec4 color = texture (uCameraTexture, vTexCoord); + // Early exit 优化:无任何调整时直接输出 + if (!uColorRecipeEnabled && !uLutEnabled) { fragColor = color; + return; } + + // === 色彩配方处理(按专业后期流程顺序) === + if (uColorRecipeEnabled) { + // 1. 曝光调整(线性空间,最先执行避免 clipping) + color.rgb *= pow(2.0, uExposure); + + // 2. 高光/阴影调整(分区调整,基于亮度 mask) + float luma = dot (color.rgb, vec3(0.299, 0.587, 0.114)); + float highlightMask = smoothstep (0.5, 1.0, luma); + float shadowMask = smoothstep (0.5, 0.0, luma); + float highlightFactor; + if (uHighlights > 0.0) { + highlightFactor = 1.0 + uHighlights * 0.7; + } else { + highlightFactor = 1.0 + uHighlights * 0.3; + } + color.rgb = mix(color.rgb, color.rgb * highlightFactor, highlightMask); + vec3 shadowTarget; + if (uShadows > 0.0) { + shadowTarget = mix(color.rgb, vec3(1.0) * luma, uShadows * 0.2) + (color.rgb * uShadows * 0.5); + } else { + shadowTarget = color.rgb * (1.0 + uShadows * 0.5); + } + color.rgb = mix(color.rgb, shadowTarget, shadowMask); + + // 3. 对比度(围绕中灰点调整) + color.rgb = (color.rgb - 0.5) * uContrast + 0.5; + + // 4. 白平衡调整(色温 + 色调) + // 色温:增加暖色调(偏红)或冷色调(偏蓝) + color.r += uTemperature * 0.1; + color.b -= uTemperature * 0.1; + // 色调:绿-品红偏移 + color.g += uTint * 0.05; + + // 5. 饱和度(基于 Luma 的快速算法,避免 HSL 转换) + float gray = dot (color.rgb, vec3(0.299, 0.587, 0.114)); + color.rgb = mix(vec3(gray), color.rgb, uSaturation); + + // 6. 色彩增强(Vibrance - 选择性增强蓝色/红橙色) + float strength = uVibrance * 0.5; + // --- 6.1 蓝色增强 (深邃天空/水面) --- + float baseBlue = color . b -(color.r + color.g) * 0.5; + float blueMask = smoothstep (0.0, 0.2, baseBlue); + if (blueMask > 0.0) { + // 增加蓝色的纯度 (使用比例混合,避免绝对值减法产生噪点) + color.r = mix(color.r, color.r * 0.7, blueMask * strength); + color.g = mix(color.g, color.g * 0.7, blueMask * strength); + // 稍微压暗蓝色,制造胶片重感 (同样使用比例混合) + color.b = mix(color.b, color.b * 0.95, blueMask * strength); + // 使用 S 曲线增加蓝色区域的对比度/通透感 + vec3 sCurve = color . rgb * color . rgb *(3.0 - 2.0 * color.rgb); + color.rgb = mix(color.rgb, sCurve, blueMask * strength * 0.2); + } + // --- 6.2 暖色增强 (新增逻辑:红润肤色/日落) --- + // 去除浑浊的蓝色杂质,呈现奶油般质感的红/橙色 + // 算法:检测红色分量是否显著高于蓝色 (捕捉皮肤、夕阳、木头等) + float baseWarm = color . r -(color.g * 0.3 + color.b * 0.7); + float warmMask = smoothstep (0.05, 0.25, baseWarm); + if (warmMask > 0.0) { + // 6.2.1 "去脏":只在一定范围内应用,避免把鲜艳的红色变黑 + color.b = mix(color.b, color.b * 0.85, warmMask * strength); + // 6.2.2 密度调整 + color.g = mix(color.g, color.g * 0.95, warmMask * strength); + // 6.2.3 胶片感增强:使用非线性缩放而不是简单的乘法,保护亮度 + vec3 sCurve = color . rgb * color . rgb *(3.0 - 2.0 * color.rgb); + color.rgb = mix(color.rgb, sCurve, warmMask * strength * 0.25); + } + + // 7. 褪色效果(降低对比度 + 提升黑电平) + if (uFade > 0.0) { + float fadeAmount = uFade * 0.3; + color.rgb = mix(color.rgb, vec3(0.5), fadeAmount); + color.rgb += fadeAmount * 0.1; + } + + // 8. 留银冲洗(Bleach Bypass - 胶片银盐保留效果) + if (uBleachBypass > 0.0) { + // 保留部分银盐:降低饱和度 + float luma = dot (color.rgb, vec3(0.299, 0.587, 0.114)); + vec3 desaturated = mix (color.rgb, vec3(luma), 0.6); + + // 增强对比度 + desaturated = (desaturated - 0.5) * 1.3 + 0.5; + + // 色调偏移到冷色调(青绿色) + desaturated.r *= 0.95; + desaturated.g *= 1.02; + desaturated.b *= 1.05; + + // 根据强度混合 + color.rgb = mix(color.rgb, desaturated, uBleachBypass); + } + + // 9. 晕影(Vignette - 边缘光线衰减/增强) + if (abs(uVignette) > 0.0) { + // 计算从中心到边缘的距离 + vec2 center = vec2 (0.5, 0.5); + float dist = distance (vTexCoord, center); + + // 使用 smoothstep 创建平滑过渡 + // 调整衰减曲线:从0.3到0.8的范围 + float vignetteMask = smoothstep (0.8, 0.3, dist); + + // 根据 uVignette 符号决定是暗角还是亮角 + if (uVignette < 0.0) { + // 暗角:边缘变暗(更强的效果:从0.01到1.0) + color.rgb *= mix(0.01, 1.0, vignetteMask) * abs(uVignette) + (1.0 + uVignette); + } else { + // 亮角:边缘变亮(增强效果) + color.rgb = mix(color.rgb, vec3(1.0), (1.0 - vignetteMask) * uVignette); + } + } + + // 10. 颗粒(Film Grain - 胶片颗粒感) + if (uFilmGrain > 0.0) { + // 使用纹理坐标生成伪随机噪声 + // 基于片段位置的简单哈希函数 + float noise = fract (sin(dot(vTexCoord * 1000.0, vec2(12.9898, 78.233))) * 43758.5453); + + // 将噪声从 [0,1] 映射到 [-1,1] + noise = (noise - 0.5) * 2.0; + + // 根据亮度自适应调整颗粒强度(高光和阴影更明显) + float luma = dot (color.rgb, vec3(0.299, 0.587, 0.114)); + float grainMask = 1.0-abs(luma-0.5) * 2.0; // 中间调弱,高光阴影强 + grainMask = grainMask * 0.5 + 0.5; // 调整到 [0.5, 1.0] 范围 + + // 应用颗粒(增强强度) + float grainStrength = uFilmGrain * 0.1 * grainMask; + color.rgb += noise * grainStrength; + } + + // Clamp 到合法范围 + color.rgb = clamp(color.rgb, 0.0, 1.0); + } + + // === LUT 处理(在色彩配方之后,保持 LUT 创作意图) === + if (uLutEnabled && uLutIntensity > 0.0) { + // 3D LUT 查找 + float scale =(uLutSize - 1.0) / uLutSize; + float offset = 1.0 / (2.0 * uLutSize); + + // 将 RGB 值映射到 LUT 纹理坐标 + vec3 lutCoord = color . rgb * scale +offset; + + // 从 3D LUT 纹理采样 + vec4 lutColor = texture (uLutTexture, lutCoord); + + // 根据强度混合色彩配方处理后的颜色和 LUT 颜色 + color.rgb = mix(color.rgb, lutColor.rgb, uLutIntensity); + } + + fragColor = color; + } """.trimIndent() - + /** * 全屏四边形的顶点坐标 * 覆盖整个屏幕 (-1, -1) 到 (1, 1) @@ -349,11 +368,11 @@ object Shaders { val FULL_QUAD_VERTICES = floatArrayOf( // X, Y -1.0f, -1.0f, // 左下 - 1.0f, -1.0f, // 右下 - -1.0f, 1.0f, // 左上 - 1.0f, 1.0f // 右上 + 1.0f, -1.0f, // 右下 + -1.0f, 1.0f, // 左上 + 1.0f, 1.0f // 右上 ) - + /** * 纹理坐标 * OpenGL 纹理坐标系:左下角为 (0, 0) @@ -365,7 +384,7 @@ object Shaders { 0.0f, 1.0f, // 左上 1.0f, 1.0f // 右上 ) - + /** * 绘制顺序索引 * 使用两个三角形绘制四边形 diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt index 15d3af1f..5068d21b 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt @@ -7,6 +7,7 @@ import android.opengl.GLSurfaceView import android.util.AttributeSet import android.util.Log import android.view.Surface +import com.hinnka.mycamera.livephoto.LivePhotoRecorder import com.hinnka.mycamera.lut.LutConfig import com.hinnka.mycamera.lut.LutRenderer import com.hinnka.mycamera.utils.PLog @@ -186,6 +187,13 @@ class CameraGLSurfaceView @JvmOverloads constructor( } } + /** + * 设置 Live Photo 录制器 + */ + fun setLivePhotoRecorder(recorder: LivePhotoRecorder?) { + renderer.livePhotoRecorder = recorder + } + override fun onPause() { super.onPause() PLog.d(TAG, "onPause") diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt index f7bfa964..3fe3f496 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt @@ -15,7 +15,9 @@ import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.viewinterop.AndroidView import com.hinnka.mycamera.camera.AspectRatio +import com.hinnka.mycamera.livephoto.LivePhotoRecorder import com.hinnka.mycamera.lut.LutConfig +import com.hinnka.mycamera.lut.LutRenderer import com.hinnka.mycamera.model.ColorRecipeParams import com.hinnka.mycamera.ui.components.FocusIndicator @@ -38,6 +40,7 @@ fun CameraPreviewGL( onSurfaceTextureReady: (SurfaceTexture) -> Unit, onSurfaceDestroyed: () -> Unit, onTap: (Float, Float, Int, Int) -> Unit, + livePhotoRecorder: LivePhotoRecorder? = null, onGLSurfaceViewReady: ((CameraGLSurfaceView) -> Unit)? = null, modifier: Modifier = Modifier ) { @@ -110,6 +113,8 @@ fun CameraPreviewGL( onSurfaceDestroyed() } + this.setLivePhotoRecorder(livePhotoRecorder) + // 通知 GLSurfaceView 已准备好 onGLSurfaceViewReady?.invoke(this) } @@ -154,6 +159,8 @@ fun CameraPreviewGL( glSurfaceView.setLutEnabled(false) glSurfaceView.setColorRecipeEnabled(false) } + + glSurfaceView.setLivePhotoRecorder(livePhotoRecorder) }, modifier = Modifier.fillMaxSize() ) diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt index 64d9e1e6..fca7a7ed 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt @@ -13,10 +13,9 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Cameraswitch -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton +import androidx.compose.material.icons.filled.Circle +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -33,6 +32,7 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.layout import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.lifecycle.Lifecycle @@ -80,6 +80,7 @@ fun CameraScreen( val useRaw by viewModel.useRaw.collectAsState() val useMultiFrame by viewModel.useMultiFrame.collectAsState() val useSuperResolution by viewModel.useSuperResolution.collectAsState() + val useLivePhoto by viewModel.useLivePhoto.collectAsState() val backgroundColor = Color(0xFF434A5D) @@ -209,9 +210,41 @@ fun CameraScreen( viewModel.focusOnPoint(x, y, w, h) } }, + livePhotoRecorder = viewModel.livePhotoRecorder, modifier = Modifier.fillMaxSize() ) + // Live Photo Indicator + if (useLivePhoto) { + Surface( + modifier = Modifier + .padding(12.dp) + .align(Alignment.TopStart), + color = Color.Yellow.copy(alpha = 0.8f), + shape = CircleShape + ) { + Row( + modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Default.Circle, + contentDescription = null, + tint = Color.Black, + modifier = Modifier.size(12.dp) + ) + Spacer(modifier = Modifier.width(4.dp)) + Text( + text = "LIVE", + color = Color.Black, + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Bold + ) + } + } + } + + Box(modifier = Modifier.fillMaxWidth().aspectRatio(3 / 4f).align(Alignment.Center)) { // 实时直方图 (Overlaid on preview if enabled) if (state.histogram != null && viewModel.showHistogram) { @@ -416,7 +449,9 @@ fun CameraScreen( viewModel.setUseMultiFrame(true) } viewModel.setUseSuperResolution(it) - } + }, + useLivePhoto = useLivePhoto, + onLivePhotoToggle = { viewModel.setUseLivePhoto(it) } ) // LutControlPanel 显示在遮罩层之上,确保能接收点击事件 diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraTopSheet.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraTopSheet.kt index 1e07e51b..09bb4d53 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraTopSheet.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraTopSheet.kt @@ -42,6 +42,8 @@ fun CameraTopSheet( onMultiFrameToggle: (Boolean) -> Unit, useSuperResolution: Boolean, onSuperResolutionToggle: (Boolean) -> Unit, + useLivePhoto: Boolean, + onLivePhotoToggle: (Boolean) -> Unit, modifier: Modifier = Modifier ) { AnimatedVisibility( @@ -142,6 +144,23 @@ fun CameraTopSheet( Spacer(modifier = Modifier.height(12.dp)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + // Live Photo Toggle + QuickSettingToggle( + title = stringResource(R.string.settings_use_live_photo), + checked = useLivePhoto, + onCheckedChange = onLivePhotoToggle, + modifier = Modifier.weight(1f) + ) + + Spacer(modifier = Modifier.weight(1f)) + } + + Spacer(modifier = Modifier.height(12.dp)) + Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp) diff --git a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt index 25f8007b..d7516700 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt @@ -76,6 +76,7 @@ fun SettingsScreen( val useMultiFrame by viewModel.useMultiFrame.collectAsState() val multiFrameCount by viewModel.multiFrameCount.collectAsState() val useSuperResolution by viewModel.useSuperResolution.collectAsState() + val useLivePhoto by viewModel.useLivePhoto.collectAsState() val rawEngine by viewModel.rawEngine.collectAsState(initial = RawEngine.NATIVE) val isPurchased by viewModel.isPurchased.collectAsState() @@ -373,6 +374,18 @@ fun SettingsScreen( checked = useSuperResolution, onCheckedChange = { viewModel.setUseSuperResolution(it) } ) + + HorizontalDivider( + color = Color.White.copy(alpha = 0.1f), + modifier = Modifier.padding(vertical = 8.dp) + ) + + SwitchSettingItem( + title = stringResource(R.string.settings_use_live_photo), + description = stringResource(R.string.settings_use_live_photo_description), + checked = useLivePhoto, + onCheckedChange = { viewModel.setUseLivePhoto(it) } + ) } HorizontalDivider( diff --git a/app/src/main/java/com/hinnka/mycamera/utils/PLog.kt b/app/src/main/java/com/hinnka/mycamera/utils/PLog.kt index 05c9d260..cde98329 100644 --- a/app/src/main/java/com/hinnka/mycamera/utils/PLog.kt +++ b/app/src/main/java/com/hinnka/mycamera/utils/PLog.kt @@ -54,7 +54,7 @@ object PLog { */ fun v(tag: String, message: String) { addLog(LogLevel.VERBOSE, tag, message) - Log.v(tag, message) + Log.v("PLog_$tag", message) } /** @@ -62,7 +62,7 @@ object PLog { */ fun d(tag: String, message: String) { addLog(LogLevel.DEBUG, tag, message) - Log.d(tag, message) + Log.d("PLog_$tag", message) } /** @@ -70,7 +70,7 @@ object PLog { */ fun i(tag: String, message: String) { addLog(LogLevel.INFO, tag, message) - Log.i(tag, message) + Log.i("PLog_$tag", message) } /** @@ -79,9 +79,9 @@ object PLog { fun w(tag: String, message: String, throwable: Throwable? = null) { addLog(LogLevel.WARNING, tag, message, throwable) if (throwable != null) { - Log.w(tag, message, throwable) + Log.w("PLog_$tag", message, throwable) } else { - Log.w(tag, message) + Log.w("PLog_$tag", message) } } @@ -91,9 +91,9 @@ object PLog { fun e(tag: String, message: String, throwable: Throwable? = null) { addLog(LogLevel.ERROR, tag, message, throwable) if (throwable != null) { - Log.e(tag, message, throwable) + Log.e("PLog_$tag", message, throwable) } else { - Log.e(tag, message) + Log.e("PLog_$tag", message) } } diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index 3f628cc0..21f09fcb 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -33,6 +33,7 @@ import com.hinnka.mycamera.utils.VibrationHelper import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import kotlinx.coroutines.flow.first +import java.io.File import kotlin.math.abs /** @@ -74,6 +75,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) private val vibrationHelper = VibrationHelper(application) val state: StateFlow = cameraController.state + val livePhotoRecorder get() = cameraController.livePhotoRecorder // 照片保存完成事件 private val _imageSavedEvent = MutableSharedFlow() @@ -149,6 +151,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false) val rawEngine: Flow = userPreferencesRepository.userPreferences .map { it.rawEngine } + val useLivePhoto: StateFlow = userPreferencesRepository.userPreferences + .map { it.useLivePhoto } + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false) // 软件处理参数 Flow val sharpening: Flow = userPreferencesRepository.userPreferences.map { it.sharpening } @@ -170,6 +175,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) // Burst State private var isBursting = false private val burstImages = mutableListOf() + private val livePhotoVideoQueue = mutableListOf>() init { cameraController.initialize() @@ -222,9 +228,18 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) cameraController.setEdgeLevel(it.edgeLevel) // 同步 RAW 设置到相机控制器 cameraController.setUseRaw(it.useRaw) + // 同步 Live Photo 设置到相机控制器 + cameraController.setUseLivePhoto(it.useLivePhoto) } } + cameraController.onLivePhotoVideoCaptured = { file, timestamp -> + val deferred = synchronized(livePhotoVideoQueue) { + if (livePhotoVideoQueue.isNotEmpty()) livePhotoVideoQueue.removeAt(0) else null + } + deferred?.complete(file) + } + // 设置快门音效和震动回调 cameraController.onPlayShutterSound = { if (isShutterSoundEnabled) { @@ -301,6 +316,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) cameraController.setUseMultiFrame(prefs.useMultiFrame, prefs.multiFrameCount) cameraController.setUseSuperResolution(prefs.useSuperResolution) + cameraController.setUseLivePhoto(prefs.useLivePhoto) } else { // 如果没有任何偏好设置,使用配置文件中的默认 LUT(第一个) val defaultLut = availableLutList.firstOrNull { it.isDefault } @@ -384,9 +400,23 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) burstImages.clear() if (useMultiFrame.value) { isBursting = true + if (useLivePhoto.value) { + val deferred = CompletableDeferred() + synchronized(livePhotoVideoQueue) { + livePhotoVideoQueue.add(deferred) + } + cameraController.captureLivePhoto(currentLutConfig, currentRecipeParams.value) + } cameraController.capture() } else { isBursting = false + if (useLivePhoto.value) { + val deferred = CompletableDeferred() + synchronized(livePhotoVideoQueue) { + livePhotoVideoQueue.add(deferred) + } + cameraController.captureLivePhoto(currentLutConfig, currentRecipeParams.value) + } // 普通拍摄:直接拍照 cameraController.capture() } @@ -843,6 +873,16 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } } + /** + * 设置是否启用 Live Photo + */ + fun setUseLivePhoto(enabled: Boolean) { + cameraController.setUseLivePhoto(enabled) + viewModelScope.launch { + userPreferencesRepository.saveUseLivePhoto(enabled) + } + } + /** * 切换延时拍摄档位(0s → 3s → 5s → 10s → 0s) */ @@ -1274,6 +1314,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) rawEngine = rawEngine.firstOrNull() ) + val livePhotoVideoDeferred = if (useLivePhoto.value) { + synchronized(livePhotoVideoQueue) { + if (livePhotoVideoQueue.isNotEmpty()) livePhotoVideoQueue.last() else null + } + } else null + val photoId = characteristics?.let { PhotoManager.savePhoto( context, @@ -1289,6 +1335,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) sharpeningValue, noiseReductionValue, chromaNoiseReductionValue, + livePhotoVideoDeferred = livePhotoVideoDeferred, onProcessingComplete = { cameraController.releaseImage(image) } ) } @@ -1361,6 +1408,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) rawEngine = rawEngine.firstOrNull() ) + val livePhotoVideoDeferred = if (useLivePhoto.value) { + synchronized(livePhotoVideoQueue) { + if (livePhotoVideoQueue.isNotEmpty()) livePhotoVideoQueue.last() else null + } + } else null + val photoId = characteristics?.let { PhotoManager.saveStackedPhoto( context, @@ -1377,6 +1430,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) noiseReductionValue, chromaNoiseReductionValue, useSuperResolution = useSuperResolution.value, + livePhotoVideoDeferred = livePhotoVideoDeferred, onProcessingComplete = { images.forEach { cameraController.releaseImage(it) } } ) } diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml index 97f0f76d..23c245e4 100644 --- a/app/src/main/res/values-zh/strings.xml +++ b/app/src/main/res/values-zh/strings.xml @@ -110,6 +110,8 @@ 选择用于处理 RAW 数据的引擎 原生 自研 + 动态照片 (Live Photo) + 在拍照时同时录制一段短视频,让照片动起来。 边框水印 边框样式 为拍摄的照片添加装饰性边框和水印 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 93082b9b..1d1dbc2d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -111,6 +111,8 @@ Choose the engine for RAW data processing Native Self-developed + Live Photo + Capture a short video clip along with your photo for a dynamic live photo effect. Frame Watermark Frame Style Add decorative frame and watermark to photos From ffc42853a102b90eac97d726aeff1e9eec73a33a Mon Sep 17 00:00:00 2001 From: Hinnka Date: Fri, 30 Jan 2026 22:38:42 +0800 Subject: [PATCH 2/2] feat: live photo 2 --- .../hinnka/mycamera/gallery/PhotoManager.kt | 4 +- .../mycamera/livephoto/LivePhotoRecorder.kt | 11 -- .../mycamera/livephoto/MotionPhotoWriter.kt | 113 +++++++----------- 3 files changed, 44 insertions(+), 84 deletions(-) diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt index 1b195471..fbffd135 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt @@ -113,9 +113,8 @@ object PhotoManager { processedBitmap ?: return@withContext // 保存到指定目录 - // Use MVIMG naming convention (classic Google Camera) as suggested by reference implementation val filename = - "MVIMG_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())}.jpg" + "PhotonCamera_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())}.jpg" val contentValues = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, filename) put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg") @@ -335,7 +334,6 @@ object PhotoManager { // 处理 Live Photo 合成 livePhotoVideoDeferred?.await()?.let { videoFile -> - Log.d(TAG, "savePhoto: livePhotoVideoDeferred") val presentationTimestampUs = 1_500_000L // 假设 1.5s 缓冲 val motionPhotoFile = File(photoDir, "motion_photo.jpg") if (MotionPhotoWriter.write( diff --git a/app/src/main/java/com/hinnka/mycamera/livephoto/LivePhotoRecorder.kt b/app/src/main/java/com/hinnka/mycamera/livephoto/LivePhotoRecorder.kt index 933a9daf..56c1c0dd 100644 --- a/app/src/main/java/com/hinnka/mycamera/livephoto/LivePhotoRecorder.kt +++ b/app/src/main/java/com/hinnka/mycamera/livephoto/LivePhotoRecorder.kt @@ -132,19 +132,8 @@ class LivePhotoRecorder( sharedContext: EGLContext ) { try { - // 限制分辨率 - val maxDim = 1280 var w = width var h = height - if (w > maxDim || h > maxDim) { - if (w > h) { - h = (h * maxDim.toFloat() / w).toInt() - w = maxDim - } else { - w = (w * maxDim.toFloat() / h).toInt() - h = maxDim - } - } // Ensure even dimensions if (w % 2 != 0) w-- diff --git a/app/src/main/java/com/hinnka/mycamera/livephoto/MotionPhotoWriter.kt b/app/src/main/java/com/hinnka/mycamera/livephoto/MotionPhotoWriter.kt index 2d15b731..a1d14c63 100644 --- a/app/src/main/java/com/hinnka/mycamera/livephoto/MotionPhotoWriter.kt +++ b/app/src/main/java/com/hinnka/mycamera/livephoto/MotionPhotoWriter.kt @@ -26,21 +26,9 @@ import java.nio.charset.StandardCharsets object MotionPhotoWriter { private const val TAG = "MotionPhotoWriter" - // JPEG 标记 - private const val JPEG_SOI = 0xFFD8 // Start of Image - private const val JPEG_EOI = 0xFFD9 // End of Image private const val JPEG_APP1 = 0xFFE1 // APP1 (EXIF/XMP) private const val JPEG_SOS = 0xFFDA // Start of Scan - // XMP 命名空间 - private const val XMP_NS_X = "adobe:ns:meta/" - private const val XMP_NS_RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" - private const val XMP_NS_CAMERA = "http://ns.google.com/photos/1.0/camera/" - private const val XMP_NS_CAMERA_XIAOMI = "http://ns.xiaomi.com/photos/1.0/camera/" - private const val XMP_NS_CAMERA_OP = "http://ns.oplus.com/photos/1.0/camera/" - private const val XMP_NS_CONTAINER = "http://ns.google.com/photos/1.0/container/" - private const val XMP_NS_ITEM = "http://ns.google.com/photos/1.0/container/item/" - /** * 合成 Motion Photo 文件 * @@ -245,64 +233,49 @@ object MotionPhotoWriter { */ private fun buildMotionPhotoXmp(videoLength: Long, presentationTimestampUs: Long): ByteArray { val xmp = buildString { - // "Dual-Metadata" Strategy: - // Reverting to Attribute-based syntax for Container Items which is standard for Google Photos. - - append("") - append("") - append("") - append("") - - // Container Directory - append("") - append("") - - // Item 1: Primary Image - append("") - append("") - append("") - - // Item 2: Motion Photo Video - append("") - append("") - append("") - - append("") - append("") - - append("") - append("") - append("") - - // Add padding (Standard is usually whitespace in the packet wrapper) - for (i in 0..2000) { - append(" ") - } - - append("") + append(""" + + + + + + + + + + + + + + + + +""") } return xmp.toByteArray(StandardCharsets.UTF_8)