From b725297dfea58d45aacde78223cf5a957135dff7 Mon Sep 17 00:00:00 2001 From: Hinnka Date: Sat, 30 May 2026 09:02:44 +0800 Subject: [PATCH] feat: support video LUT and color recipe editing --- app/build.gradle.kts | 4 +- .../java/com/hinnka/mycamera/MainActivity.kt | 4 +- .../hinnka/mycamera/gallery/GalleryManager.kt | 36 +- .../mycamera/gallery/db/GalleryMediaStore.kt | 5 +- .../com/hinnka/mycamera/lut/VideoExporter.kt | 243 ++++ .../com/hinnka/mycamera/lut/VideoLutEffect.kt | 1003 +++++++++++++++++ .../ui/gallery/GalleryDetailScreen.kt | 200 +++- ...hotoEditScreen.kt => GalleryEditScreen.kt} | 409 ++++--- .../mycamera/viewmodel/GalleryViewModel.kt | 162 ++- app/src/main/res/values-zh-rCN/strings.xml | 5 + app/src/main/res/values/strings.xml | 5 + gradle/libs.versions.toml | 2 + 12 files changed, 1855 insertions(+), 223 deletions(-) create mode 100644 app/src/main/java/com/hinnka/mycamera/lut/VideoExporter.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/lut/VideoLutEffect.kt rename app/src/main/java/com/hinnka/mycamera/ui/gallery/{PhotoEditScreen.kt => GalleryEditScreen.kt} (81%) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index a73cefa3..be178a76 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -222,9 +222,11 @@ dependencies { // Reorderable for drag-and-drop list reordering implementation("sh.calvin.reorderable:reorderable:2.4.3") - // Media3 for video playback + // Media3 for video playback and export implementation(libs.media3.exoplayer) implementation(libs.media3.ui) + implementation(libs.media3.effect) + implementation(libs.media3.transformer) testImplementation(libs.junit) androidTestImplementation(libs.androidx.junit) diff --git a/app/src/main/java/com/hinnka/mycamera/MainActivity.kt b/app/src/main/java/com/hinnka/mycamera/MainActivity.kt index e9b4065a..0376ff09 100644 --- a/app/src/main/java/com/hinnka/mycamera/MainActivity.kt +++ b/app/src/main/java/com/hinnka/mycamera/MainActivity.kt @@ -78,7 +78,7 @@ import com.hinnka.mycamera.ui.camera.PuzzleScreen import com.hinnka.mycamera.ui.gallery.BurstDetailScreen import com.hinnka.mycamera.ui.gallery.GalleryDetailScreen import com.hinnka.mycamera.ui.gallery.GalleryScreen -import com.hinnka.mycamera.ui.gallery.PhotoEditScreen +import com.hinnka.mycamera.ui.gallery.GalleryEditScreen import com.hinnka.mycamera.ui.settings.FilterManagementScreen import com.hinnka.mycamera.ui.settings.FrameEditorScreen import com.hinnka.mycamera.ui.settings.FrameManagementScreen @@ -634,7 +634,7 @@ fun NavigationHost( } composable(Routes.PHOTO_EDIT) { - PhotoEditScreen( + GalleryEditScreen( viewModel = galleryViewModel, cameraViewModel = cameraViewModel, onBack = { diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt index 7d40590c..0906ef6b 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt @@ -2631,9 +2631,43 @@ object GalleryManager { sourceUri = uri.toString() ) - // 1. 检测是否为 RAW 文件 + // 1. 检测是否为 RAW 或视频文件 val mimeType = context.contentResolver.getType(uri) val fileName = getFileName(context, uri) ?: "" + val isVideo = mimeType?.startsWith("video/") == true + + if (isVideo) { + val info = readVideoRecordInfo(context, uri) ?: return@withContext null + val videoMetadata = MediaMetadata( + mediaType = MediaType.VIDEO, + dateTaken = info.dateTaken, + width = info.width, + height = info.height, + sourceUri = uri.toString(), + mimeType = info.mimeType, + durationMs = info.durationMs, + frameRate = info.frameRate, + bitrate = info.bitrate, + rotationDegrees = info.rotationDegrees, + hasAudio = info.hasAudio, + videoWidth = info.width, + videoHeight = info.height, + captureMode = "video", + isImported = true + ) + val thumbnailSaved = saveVideoThumbnail(context, uri, thumbnailFile) + if (!thumbnailSaved) { + PLog.w(TAG, "Video thumbnail not generated for imported video $uri") + } + val metadataSaved = saveMetadata(context, photoId, videoMetadata) + if (!metadataSaved) { + photoDir.deleteRecursively() + return@withContext null + } + notifyPhotoLibraryChanged() + return@withContext photoId + } + val userPrefs = ContentRepository.getInstance(context).userPreferencesRepository.userPreferences.firstOrNull() val isRaw = mimeType?.contains("raw", ignoreCase = true) == true || diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaStore.kt b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaStore.kt index 04c906d3..cefe78f9 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaStore.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaStore.kt @@ -164,10 +164,9 @@ object GalleryMediaStore { val originalFile = dngFile.takeIf { it.exists() } ?: yuvFile.takeIf { it.exists() } ?: photoFile val isVideo = metadata.mediaType == MediaType.VIDEO val dateAdded = if (isVideo) { - metadata.dateTaken ?: photoDir.lastModified().takeIf { it > 0L } ?: System.currentTimeMillis() + photoDir.lastModified().takeIf { it > 0L } ?: System.currentTimeMillis() } else { originalFile.lastModified().takeIf { originalFile.exists() && it > 0L } - ?: metadata.dateTaken ?: photoDir.lastModified().takeIf { it > 0L } ?: System.currentTimeMillis() } @@ -285,7 +284,7 @@ object GalleryMediaStore { uri = resolvedSourceUri, thumbnailUri = thumbnailUri, displayName = resolvedSourceUri.lastPathSegment ?: "video_$id", - dateAdded = dateTaken ?: dateAdded, + dateAdded = dateAdded, size = size, width = videoWidth ?: width, height = videoHeight ?: height, diff --git a/app/src/main/java/com/hinnka/mycamera/lut/VideoExporter.kt b/app/src/main/java/com/hinnka/mycamera/lut/VideoExporter.kt new file mode 100644 index 00000000..93cc81de --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/VideoExporter.kt @@ -0,0 +1,243 @@ +package com.hinnka.mycamera.lut + +import android.content.ContentValues +import android.content.Context +import android.media.MediaMetadataRetriever +import android.net.Uri +import android.os.Environment +import android.provider.MediaStore +import androidx.media3.common.MediaItem +import androidx.media3.common.MimeTypes +import androidx.media3.common.util.UnstableApi +import androidx.media3.transformer.Composition +import androidx.media3.transformer.ExportException +import androidx.media3.transformer.ExportResult +import androidx.media3.transformer.ProgressHolder +import androidx.media3.transformer.Transformer +import androidx.media3.transformer.EditedMediaItem +import androidx.media3.transformer.Effects +import com.hinnka.mycamera.model.ColorRecipeParams +import com.hinnka.mycamera.utils.PLog +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext +import java.io.File +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import kotlin.coroutines.resume + +private const val TAG = "VideoExporter" + +/** + * 视频导出器:使用 Media3 Transformer 将 LUT / 色彩配方 GL 效果烘焙到视频文件中并保存到相册。 + * + * @param context 应用上下文 + * @param inputUri 原始视频 URI(MediaStore 或文件 URI) + * @param lutConfig LUT 配置(可为空,表示仅应用色彩配方) + * @param recipeParams 色彩配方参数(可为空) + * @param outputDisplayName 导出文件名(不含扩展名),默认按时间戳生成 + * @param onProgress 进度回调(0..100),在主线程调用 + * @return 导出成功后写入 MediaStore 的 URI;失败返回 null + */ +@UnstableApi +suspend fun exportVideoWithEffects( + context: Context, + inputUri: Uri, + lutConfig: LutConfig?, + recipeParams: ColorRecipeParams?, + outputDisplayName: String? = null, + onProgress: ((Int) -> Unit)? = null, +): Uri? = withContext(Dispatchers.Main) { + // 检测原始视频编码,决定输出 MIME + val originalMime = detectVideoMime(context, inputUri) + PLog.d(TAG, "Input video MIME: $originalMime") + + // 构建临时输出文件 + val tempDir = File(context.cacheDir, "video_export").also { it.mkdirs() } + val tempFile = File(tempDir, "export_${System.nanoTime()}.mp4") + + try { + // 构建 VideoLutEffect + val effect = VideoLutEffect(lutConfig, recipeParams) + + // 构建 EditedMediaItem,注入 GL 效果 + val mediaItem = MediaItem.fromUri(inputUri) + val editedMediaItem = EditedMediaItem.Builder(mediaItem) + .setEffects( + Effects( + /* audioProcessors= */ emptyList(), + /* videoEffects= */ listOf(effect) + ) + ) + .build() + + // 构建 Transformer + val transformer = Transformer.Builder(context) + .also { builder -> + // 优先保留原始编码,不指定 videoMimeType 则 Transformer 自动保留 + // 若原始为 HEVC 则尝试输出 HEVC,否则回落到 H264 + val targetMime = when { + originalMime == MimeTypes.VIDEO_H265 -> MimeTypes.VIDEO_H265 + else -> MimeTypes.VIDEO_H264 + } + PLog.d(TAG, "Target video MIME: $targetMime") + builder.setVideoMimeType(targetMime) + } + .build() + + // 执行转码(挂起,直到完成或出错) + val exportResult = runTransformer( + transformer = transformer, + editedMediaItem = editedMediaItem, + outputPath = tempFile.absolutePath, + onProgress = onProgress + ) + + if (exportResult == null) { + PLog.e(TAG, "Transformer returned null result (export failed or cancelled)") + return@withContext null + } + + PLog.d(TAG, "Transformer succeeded, output size: ${tempFile.length()} bytes") + + // 将临时文件写入 MediaStore Movies/PhotonCamera/ + val displayName = outputDisplayName + ?: "PhotonCamera_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())}_edit" + val savedUri = saveVideoToMediaStore(context, tempFile, "$displayName.mp4") + PLog.d(TAG, "Video saved to MediaStore: $savedUri") + savedUri + } catch (e: CancellationException) { + PLog.d(TAG, "Video export cancelled") + throw e + } catch (e: Exception) { + PLog.e(TAG, "Video export failed", e) + null + } finally { + tempFile.delete() + } +} + +/** + * 在协程中运行 Transformer,通过 listener 回调转为 suspend 函数。 + * 同时轮询进度并上报给 [onProgress]。 + * 返回 ExportResult(成功)或 null(失败/取消)。 + */ +@UnstableApi +private suspend fun runTransformer( + transformer: Transformer, + editedMediaItem: EditedMediaItem, + outputPath: String, + onProgress: ((Int) -> Unit)? +): ExportResult? = suspendCancellableCoroutine { cont -> + var completed = false + + val listener = object : Transformer.Listener { + override fun onCompleted(composition: Composition, exportResult: ExportResult) { + if (!completed) { + completed = true + PLog.d(TAG, "Transformer.onCompleted") + onProgress?.invoke(100) + cont.resume(exportResult) + } + } + + override fun onError( + composition: Composition, + exportResult: ExportResult, + exportException: ExportException + ) { + if (!completed) { + completed = true + PLog.e(TAG, "Transformer.onError: ${exportException.errorCode}", exportException) + cont.resume(null) + } + } + } + + transformer.addListener(listener) + transformer.start(editedMediaItem, outputPath) + PLog.d(TAG, "Transformer started, outputPath: $outputPath") + + // 在取消时停止 Transformer + cont.invokeOnCancellation { + PLog.d(TAG, "Cancelling transformer") + transformer.cancel() + } + + // 启动进度轮询协程(在同一个 cont 作用域外需另起,这里用 Thread 简单实现) + if (onProgress != null) { + Thread { + val progressHolder = ProgressHolder() + while (!completed) { + try { + @Suppress("BlockingMethodInNonBlockingContext") + Thread.sleep(300) + val state = transformer.getProgress(progressHolder) + if (state == Transformer.PROGRESS_STATE_AVAILABLE) { + onProgress(progressHolder.progress) + } + } catch (_: InterruptedException) { + break + } catch (_: Exception) { + break + } + } + }.also { it.isDaemon = true }.start() + } +} + +/** + * 检测视频的编码 MIME 类型(用于决定输出编码)。 + */ +private fun detectVideoMime(context: Context, uri: Uri): String? { + return try { + val retriever = MediaMetadataRetriever() + retriever.use { + it.setDataSource(context, uri) + it.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE) + } + } catch (e: Exception) { + PLog.w(TAG, "Failed to detect video MIME: ${e.message}") + null + } +} + +/** + * 将临时文件插入 MediaStore(Movies/PhotonCamera/)。 + */ +private suspend fun saveVideoToMediaStore( + context: Context, + sourceFile: File, + displayName: String +): Uri? = withContext(Dispatchers.IO) { + try { + val contentValues = ContentValues().apply { + put(MediaStore.MediaColumns.DISPLAY_NAME, displayName) + put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4") + put( + MediaStore.MediaColumns.RELATIVE_PATH, + Environment.DIRECTORY_MOVIES + "/PhotonCamera" + ) + } + + val uri = context.contentResolver.insert( + MediaStore.Video.Media.EXTERNAL_CONTENT_URI, + contentValues + ) ?: return@withContext null + + context.contentResolver.openOutputStream(uri)?.use { out -> + sourceFile.inputStream().use { input -> + input.copyTo(out) + } + } + + uri + } catch (e: Exception) { + PLog.e(TAG, "Failed to save video to MediaStore", e) + null + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/VideoLutEffect.kt b/app/src/main/java/com/hinnka/mycamera/lut/VideoLutEffect.kt new file mode 100644 index 00000000..4c8d24ea --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/VideoLutEffect.kt @@ -0,0 +1,1003 @@ +package com.hinnka.mycamera.lut + +import android.content.Context +import android.opengl.GLES30 +import androidx.media3.common.VideoFrameProcessingException +import androidx.media3.common.util.Size +import androidx.media3.common.util.UnstableApi +import androidx.media3.effect.BaseGlShaderProgram +import androidx.media3.effect.GlEffect +import androidx.media3.effect.GlShaderProgram +import com.hinnka.mycamera.model.ColorRecipeParams +import com.hinnka.mycamera.utils.PLog +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/** + * 视频 LUT & 色彩配方 GL 效果处理器 (Media3 管线集成) + */ +@UnstableApi +class VideoLutEffect( + @Volatile var lutConfig: LutConfig?, + @Volatile var recipeParams: ColorRecipeParams? +) : GlEffect { + + private var shaderProgram: VideoLutShaderProgram? = null + + override fun toGlShaderProgram(context: Context, useHdr: Boolean): GlShaderProgram { + PLog.d("VideoLutEffect", "toGlShaderProgram called, useHdr: $useHdr, initialLut: ${lutConfig?.title}, recipeEnabled: ${recipeParams != null}") + return VideoLutShaderProgram(context, useHdr, this).also { + shaderProgram = it + } + } + + /** + * 动态更新 LUT 及其配方参数 + */ + fun update(lutConfig: LutConfig?, recipeParams: ColorRecipeParams?) { + PLog.d("VideoLutEffect", "update called, lutConfig: ${lutConfig?.title}, recipeParams: ${recipeParams != null}") + this.lutConfig = lutConfig + this.recipeParams = recipeParams + shaderProgram?.triggerUpdate() + } +} + +/** + * GLSL 着色器渲染程序 + */ +@UnstableApi +private class VideoLutShaderProgram( + private val context: Context, + useHdr: Boolean, + private val effect: VideoLutEffect +) : BaseGlShaderProgram(useHdr, /* texturePoolCapacity= */ 1) { + + companion object { + private const val TAG = "VideoLutShaderProgram" + private const val LCH_COLOR_BAND_COUNT = 9 + + private val VERTEX_SHADER = """ + #version 300 es + in vec4 aPosition; + in vec2 aTexCoord; + out vec2 vTexCoord; + void main() { + gl_Position = aPosition; + vTexCoord = aTexCoord; + } + """.trimIndent() + + private val FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + + in vec2 vTexCoord; + out vec4 fragColor; + + uniform sampler2D uImageTexture; + uniform mediump sampler3D uLutTexture; + + uniform float uLutSize; + uniform float uLutIntensity; + uniform int uLutEnabled; + uniform int uLutMaskType; + uniform int uLutCurve; + uniform int uLutColorSpace; + uniform int uInputColorSpace; + uniform int uIsHlgInput; + + // 色彩配方控制 + uniform int uColorRecipeEnabled; + + // 色彩配方参数 + uniform float uExposure; // -2.0 ~ +2.0 (EV) + uniform float uContrast; // 0.5 ~ 1.5 + uniform float uSaturation; // 0.0 ~ 2.0 + 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 + uniform float uHighlights; // -1.0 ~ +1.0 + uniform float uShadows; // -1.0 ~ +1.0 + uniform float uToneToe; // -1.0 ~ +1.0 + uniform float uToneShoulder; // -1.0 ~ +1.0 + uniform float uTonePivot; // -1.0 ~ +1.0 + uniform float uFilmGrain; // 0.0 ~ 1.0 + uniform float uVignette; // -1.0 ~ +1.0 + uniform float uBleachBypass; // 0.0 ~ 1.0 + uniform float uNoise; // 0.0 ~ 1.0 + uniform float uNoiseSeed; // 噪点随机种子 + uniform float uLowRes; // 0.0 ~ 1.0 + uniform float uAspectRatio; // 图像长宽比 + + uniform vec3 uPrimaryCalibrationRow0; + uniform vec3 uPrimaryCalibrationRow1; + uniform vec3 uPrimaryCalibrationRow2; + + uniform float uLchHueAdjustments[9]; + uniform float uLchChromaAdjustments[9]; + uniform float uLchLightnessAdjustments[9]; + uniform sampler2D uCurveTexture; + uniform int uCurveEnabled; + + uniform float uChromaticAberration; // 0.0 ~ 1.0 + uniform float uSharpening; + uniform vec2 uTexelSize; + + const float PI = 3.14159265359; + + float getLuma(vec3 color) { + vec3 weights = (uInputColorSpace == 1) ? vec3(0.2290, 0.6917, 0.0793) : vec3(0.2126, 0.7152, 0.0722); + return dot(color, weights); + } + + float log10(float x) { return log(x) * 0.4342944819; } + vec3 log10(vec3 x) { return log(x) * 0.4342944819; } + + vec3 linearToSrgb(vec3 l) { + vec3 absL = abs(l); + vec3 result = mix(absL * 12.92, 1.055 * pow(absL, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, absL)); + return sign(l) * result; + } + + vec3 srgbToLinear(vec3 c) { + vec3 absC = abs(c); + vec3 result = mix(absC / 12.92, pow((absC + 0.055) / 1.055, vec3(2.4)), step(0.04045, absC)); + return sign(c) * result; + } + + vec3 hlgToLinear(vec3 e) { + float ha = 0.17883277; + float hb = 1.0 - 4.0 * ha; + float hc = 0.5 - ha * log(4.0 * ha); + vec3 low = e * e / 3.0; + vec3 high = (exp((e - hc) / ha) + hb) / 12.0; + return mix(low, high, step(vec3(0.5), e)); + } + + vec3 bt2020ToLinearSrgb(vec3 rgb) { + return mat3( + 1.660491, -0.124550, -0.018151, + -0.587641, 1.132900, -0.100579, + -0.072850, -0.008350, 1.118730 + ) * rgb; + } + + vec3 applyExposureInLinearSpace(vec3 srgbColor, float exposureEv) { + vec3 linearColor = srgbToLinear(max(srgbColor, vec3(0.0))); + linearColor *= exp2(exposureEv); + return linearToSrgb(linearColor); + } + + float sanitizeFloat(float value) { + if (value != value) return 0.0; + return value; + } + + vec3 sanitizeColor(vec3 color) { + return vec3( + sanitizeFloat(color.r), + sanitizeFloat(color.g), + sanitizeFloat(color.b) + ); + } + + float applyToneCurveToLuma(float luma, float toe, float shoulder, float pivot) { + float safeLuma = clamp(luma, 0.0, 1.0); + float pivotPoint = clamp(0.5 + pivot * 0.12, 0.2, 0.8); + float toeAmount = clamp(abs(toe), 0.0, 1.0); + float shoulderAmount = clamp(abs(shoulder), 0.0, 1.0); + float toeGamma = (toe >= 0.0) ? mix(1.0, 0.68, toeAmount) : mix(1.0, 1.85, toeAmount); + float shoulderGamma = (shoulder >= 0.0) ? mix(1.0, 0.72, shoulderAmount) : mix(1.0, 1.85, shoulderAmount); + + if (safeLuma <= pivotPoint) { + float segment = clamp(safeLuma / max(pivotPoint, 0.0001), 0.0, 1.0); + return clamp(pow(segment, toeGamma) * pivotPoint, 0.0, 1.0); + } + + float segment = clamp((safeLuma - pivotPoint) / max(1.0 - pivotPoint, 0.0001), 0.0, 1.0); + float result = 1.0 - pow(max(0.0, 1.0 - segment), shoulderGamma) * (1.0 - pivotPoint); + return clamp(result, 0.0, 1.0); + } + + vec3 applyToneCurve(vec3 color, float toe, float shoulder, float pivot) { + if (abs(toe) < 0.001 && abs(shoulder) < 0.001 && abs(pivot) < 0.001) { + return color; + } + vec3 nonNegativeColor = max(color, vec3(0.0)); + vec3 curveSampleColor = clamp(nonNegativeColor, 0.0, 1.0); + float luma = getLuma(curveSampleColor); + float peak = max(curveSampleColor.r, max(curveSampleColor.g, curveSampleColor.b)); + float toneSignal = mix(luma, peak, 0.65); + float curvedSignal = applyToneCurveToLuma(toneSignal, toe, shoulder, pivot); + if (toneSignal < 0.0001) { + return curveSampleColor; + } + float safeRatio = clamp(curvedSignal / max(toneSignal, 0.0001), 0.0, 16.0); + vec3 scaled = nonNegativeColor * safeRatio; + return sanitizeColor(mix(vec3(curvedSignal), scaled, 0.96)); + } + + vec3 linearRgbToOklab(vec3 c) { + vec3 lms = mat3( + 0.4122214708, 0.2119034982, 0.0883024619, + 0.5363325363, 0.6806995451, 0.2817188376, + 0.0514459929, 0.1073969566, 0.6299787005 + ) * c; + vec3 lmsCbrt = pow(max(lms, vec3(0.0)), vec3(1.0 / 3.0)); + return mat3( + 0.2104542553, 1.9779984951, 0.0259040371, + 0.7936177850, -2.4285922050, 0.7827717662, + -0.0040720468, 0.4505937099, -0.8086757660 + ) * lmsCbrt; + } + + vec3 oklabToLinearRgb(vec3 lab) { + vec3 lms = mat3( + 1.0, 1.0, 1.0, + 0.3963377774, -0.1055613458, -0.0894841775, + 0.2158037573, -0.0638541728, -1.2914855480 + ) * lab; + vec3 lms3 = lms * lms * lms; + return mat3( + 4.0767416621, -1.2684380046, -0.0041960863, + -3.3077115913, 2.6097574011, -0.7034186147, + 0.2309699292, -0.3413193965, 1.7076147010 + ) * lms3; + } + + vec3 linearRgbToCieLab(vec3 linearRgb) { + vec3 xyz = mat3( + 0.4124564, 0.2126729, 0.0193339, + 0.3575761, 0.7151522, 0.1191920, + 0.1804375, 0.0721750, 0.9503041 + ) * clamp(linearRgb, 0.0, 1.0); + xyz /= vec3(0.95047, 1.0, 1.08883); + vec3 f = mix(7.787037 * xyz + vec3(16.0 / 116.0), pow(max(xyz, vec3(0.0)), vec3(1.0 / 3.0)), step(vec3(0.008856), xyz)); + return vec3(116.0 * f.y - 16.0, 500.0 * (f.x - f.y), 200.0 * (f.y - f.z)); + } + + float wrapAngle(float angle) { + return mod(angle + PI, 2.0 * PI) - PI; + } + + float fullCoverageBandWeight(float hue, float center, float chroma) { + float dist = abs(wrapAngle(hue - center)); + float hueWeight = smoothstep(radians(85.0), 0.0, dist); + float chromaWeight = smoothstep(0.005, 0.03, chroma); + return hueWeight * chromaWeight; + } + + float rtRange(float value, float minValue, float maxValue) { + return step(minValue, value) * (1.0 - step(maxValue, value)); + } + + float rtSkinCase(float l, float h, float c, float lMin, float lMax, float hMin, float hMax, float cMin, float cMax, float weight) { + return rtRange(l, lMin, lMax) * rtRange(h, hMin, hMax) * rtRange(c, cMin, cMax) * weight; + } + + float skinBandWeight(vec3 linearColor) { + vec3 lab = linearRgbToCieLab(linearColor); + float l = lab.x; + float h = atan(lab.z, lab.y); + float c = length(lab.yz); + float core = 1.0; + float extended = 0.67; + float transition = 0.33; + float w = 0.0; + + w = max(w, rtSkinCase(l, h, c, 85.0, 100.0, 0.73, 1.23, 8.0, 22.0, core)); + w = max(w, rtSkinCase(l, h, c, 92.0, 100.0, 0.80, 1.65, 7.0, 15.0, extended)); + w = max(w, rtSkinCase(l, h, c, 92.0, 100.0, -0.10, 1.65, 7.0, 18.0, transition)); + w = max(w, rtSkinCase(l, h, c, 85.0, 92.0, 0.70, 1.40, 7.0, 34.0, extended)); + w = max(w, rtSkinCase(l, h, c, 85.0, 92.0, 0.00, 1.65, 7.0, 43.0, transition)); + + w = max(w, rtSkinCase(l, h, c, 70.0, 85.0, 0.40, 1.29, 8.0, 50.0, core)); + w = max(w, rtSkinCase(l, h, c, 70.0, 85.0, -0.18, 1.50, 7.0, 56.0, extended)); + w = max(w, rtSkinCase(l, h, c, 70.0, 85.0, -0.18, 1.65, 7.0, 63.0, transition)); + + w = max(w, rtSkinCase(l, h, c, 52.0, 70.0, 0.30, 1.37, 11.0, 47.0, core)); + w = max(w, rtSkinCase(l, h, c, 52.0, 70.0, -0.18, 1.50, 7.0, 56.0, extended)); + w = max(w, rtSkinCase(l, h, c, 52.0, 70.0, -0.18, 1.65, 7.0, 63.0, transition)); + + w = max(w, rtSkinCase(l, h, c, 35.0, 52.0, 0.30, 1.27, 13.0, 44.0, core)); + w = max(w, rtSkinCase(l, h, c, 35.0, 52.0, -0.18, 1.50, 7.0, 56.0, extended)); + w = max(w, rtSkinCase(l, h, c, 35.0, 52.0, -0.18, 1.65, 7.0, 63.0, transition)); + + w = max(w, rtSkinCase(l, h, c, 20.0, 35.0, 0.30, 1.22, 7.0, 40.0, core)); + w = max(w, rtSkinCase(l, h, c, 20.0, 35.0, -0.18, 1.50, 7.0, 56.0, extended)); + w = max(w, rtSkinCase(l, h, c, 20.0, 35.0, -0.18, 1.65, 7.0, 63.0, transition)); + + w = max(w, rtSkinCase(l, h, c, 10.0, 20.0, -0.20, 1.05, 8.0, 28.0, core)); + w = max(w, rtSkinCase(l, h, c, 10.0, 20.0, -0.18, 1.00, 7.0, 40.0, extended)); + w = max(w, rtSkinCase(l, h, c, 10.0, 20.0, -0.18, 1.60, 7.0, 50.0, transition)); + + w = max(w, rtSkinCase(l, h, c, 0.0, 10.0, -0.18, 1.00, 8.0, 28.0, core)); + w = max(w, rtSkinCase(l, h, c, 0.0, 10.0, -0.18, 1.00, 7.0, 40.0, extended)); + w = max(w, rtSkinCase(l, h, c, 0.0, 10.0, -0.18, 1.60, 7.0, 50.0, transition)); + return w; + } + + float skyBandWeight(vec3 linearColor) { + vec3 lab = linearRgbToCieLab(linearColor); + float l = lab.x; + float h = atan(lab.z, lab.y); + float c = length(lab.yz); + float rtWaveletSkyHue = rtRange(h, -2.60, -1.30); + float chromaGate = smoothstep(7.0, 18.0, c); + float lightnessGate = smoothstep(18.0, 45.0, l); + return rtWaveletSkyHue * chromaGate * lightnessGate; + } + + float lutMaskWeight(int maskType, vec3 linearColor) { + if (maskType == 1) { + return skinBandWeight(linearColor); + } + if (maskType == 2) { + return skyBandWeight(linearColor); + } + return 1.0; + } + + vec3 applyOklchDensity(vec3 srgbColor, float density) { + if (abs(density) < 0.0001) { + return srgbColor; + } + + vec3 linearColor = srgbToLinear(max(srgbColor, vec3(0.0))); + vec3 lab = linearRgbToOklab(linearColor); + float chroma = length(lab.yz); + float hue = atan(lab.z, lab.y); + const float CHROMA_BIAS = 0.35; + float densityScale = max(0.0, 1.0 + density * CHROMA_BIAS); + float newChroma = chroma * densityScale; + const float DENSITY_K = 1.85; + float newLightness = clamp(lab.x * exp(-DENSITY_K * density * chroma), 0.0, 1.0); + vec3 denseLab = vec3(newLightness, cos(hue) * newChroma, sin(hue) * newChroma); + vec3 denseLinear = max(oklabToLinearRgb(denseLab), vec3(0.0)); + return linearToSrgb(denseLinear); + } + + vec3 applyLchColorMixer(vec3 srgbColor) { + vec3 linearColor = srgbToLinear(max(srgbColor, vec3(0.0))); + vec3 lab = linearRgbToOklab(linearColor); + float chroma = length(lab.yz); + float hue = atan(lab.z, lab.y); + if (hue < 0.0) hue += 2.0 * PI; + + float centers[8] = float[]( + radians(29.0), // Red + radians(52.0), // Orange + radians(86.0), // Yellow + radians(144.0), // Green + radians(196.0), // Aqua/Cyan + radians(263.0), // Blue + radians(304.0), // Purple + radians(341.0) // Magenta + ); + + float hueShift = 0.0; + float chromaScale = 1.0; + float lightnessShift = 0.0; + float bandWeights[8]; + float totalBandWeight = 0.0; + + for (int i = 0; i < 8; i++) { + float weight = fullCoverageBandWeight(hue, centers[i], chroma); + bandWeights[i] = weight; + totalBandWeight += weight; + } + + if (totalBandWeight > 0.0001) { + for (int i = 0; i < 8; i++) { + float weight = bandWeights[i] / totalBandWeight; + hueShift += uLchHueAdjustments[i + 1] * weight * radians(20.0); + chromaScale += uLchChromaAdjustments[i + 1] * weight; + lightnessShift += uLchLightnessAdjustments[i + 1] * weight * 0.15; + } + + float commonChromaWeight = smoothstep(0.005, 0.03, chroma); + hueShift *= commonChromaWeight; + chromaScale = mix(1.0, chromaScale, commonChromaWeight); + lightnessShift *= commonChromaWeight; + } + + float skinWeight = skinBandWeight(linearColor); + if (skinWeight > 0.0001) { + hueShift += uLchHueAdjustments[0] * skinWeight * radians(10.0); + chromaScale += uLchChromaAdjustments[0] * skinWeight; + lightnessShift += uLchLightnessAdjustments[0] * skinWeight * 0.08; + } + + if (abs(hueShift) < 0.0001 && abs(chromaScale - 1.0) < 0.0001 && abs(lightnessShift) < 0.0001) { + return srgbColor; + } + + float newHue = hue + hueShift; + float newChroma = max(0.0, chroma * max(0.0, chromaScale)); + float newLightness = clamp(lab.x + lightnessShift, 0.0, 1.0); + vec3 mixedLab = vec3(newLightness, cos(newHue) * newChroma, sin(newHue) * newChroma); + vec3 mixedLinear = max(oklabToLinearRgb(mixedLab), vec3(0.0)); + return linearToSrgb(mixedLinear); + } + + vec3 applyPrimaryCalibration(vec3 color) { + vec3 linearColor = srgbToLinear(max(color, vec3(0.0))); + vec3 calibratedLinear = vec3( + dot(uPrimaryCalibrationRow0, linearColor), + dot(uPrimaryCalibrationRow1, linearColor), + dot(uPrimaryCalibrationRow2, linearColor) + ); + return linearToSrgb(max(calibratedLinear, vec3(0.0))); + } + + vec3 applyLutCurve(vec3 l, int curveType) { + if (curveType == 0) return linearToSrgb(l); + if (curveType == 1) return l; + if (curveType == 2) { + return mix(5.6 * l + 0.125, 0.241514 * log10(l + 0.00873) + 0.598206, step(0.01, l)); + } + if (curveType == 3) { + return mix((l * (171.2102946929 - 95.0) / 0.01125 + 95.0) / 1023.0, (420.0 + log10((l + 0.01) / (0.18 + 0.01)) * 261.5) / 1023.0, step(0.01125, l)); + } + if (curveType == 4) { + return mix(8.799461 * l + 0.092864, 0.245281 * log10(5.555556 * l + 0.064829) + 0.384316, step(0.00089, l)); + } + if (curveType == 5) { + return mix(8.80302 * l + 0.158957, 0.21524584 * log10(2231.8263 * l + 64.0) - 0.29590839, step(-0.018057, l)); + } + if (curveType == 6) { + return mix(mix(vec3(0.0), 47.28711236 * pow(l + 0.05641088, vec3(2.0)), step(-0.05641088, l)), 0.08550479 * (log(l + 0.00964052) / log(2.0)) + 0.69336945, step(0.01, l)); + } + if (curveType == 7) { + float ha = 0.17883277; + float hb = 1.0 - 4.0 * ha; + float hc = 0.5 - ha * log(4.0 * ha); + return mix(sqrt(3.0 * l), ha * log(12.0 * l - hb) + hc, step(1.0 / 12.0, l)); + } + if (curveType == 8) { + return mix(10.540237 * l + 0.072905536, 0.18955931 * log10(max(l, vec3(1e-6))) + 0.5547945, step(0.0078125, l)); + } + return l; + } + + vec3 applyLutColorSpace(vec3 rgb, int colorSpace) { + if (colorSpace == 0) return rgb; + if (colorSpace == 1) { + return mat3(0.875905, 0.035332, 0.016382, 0.122070, 0.964542, 0.063767, 0.002025, 0.000126, 0.919851) * rgb; + } + if (colorSpace == 2) { + return mat3(0.627404, 0.069097, 0.016391, 0.329283, 0.919540, 0.088013, 0.043313, 0.011362, 0.895595) * rgb; + } + if (colorSpace == 3) { + return mat3(0.565837, 0.088626, 0.017750, 0.340331, 0.809347, 0.109448, 0.093832, 0.102028, 0.872802) * rgb; + } + if (colorSpace == 4) { + return mat3(0.608104, 0.062316, 0.031133, 0.259353, 0.804609, 0.133756, 0.132543, 0.133076, 0.835112) * rgb; + } + if (colorSpace == 5) { + return mat3(0.645679, 0.087530, 0.036957, 0.259115, 0.759700, 0.129281, 0.095206, 0.152770, 0.833762) * rgb; + } + if (colorSpace == 6) { + return mat3(0.613083, 0.070004, 0.020491, 0.341167, 0.918063, 0.106764, 0.045750, 0.011934, 0.872745) * rgb; + } + if (colorSpace == 7) { + return mat3(0.585196, 0.078589, 0.022794, 0.322642, 0.819627, 0.114217, 0.092162, 0.101784, 0.862989) * rgb; + } + return rgb; + } + + void main() { + vec2 uvCoord = vTexCoord; + if (uLowRes > 0.005) { + float blocksX = mix(512.0, 32.0, uLowRes); + vec2 gridSize = vec2(1.0 / blocksX, 1.0 / (blocksX / uAspectRatio)); + vec2 gridUV = floor(vTexCoord / gridSize) * gridSize + gridSize * 0.5; + uvCoord = mix(vTexCoord, gridUV, 0.95); + } + + vec4 color; + if (uChromaticAberration > 0.0) { + vec2 center = vec2(0.5); + vec2 dir = uvCoord - center; + float dist = length(dir); + float offset = pow(dist, 1.5) * uChromaticAberration * 0.08; + vec2 rUV = uvCoord + dir * offset; + vec2 bUV = uvCoord - dir * offset; + float r = texture(uImageTexture, rUV).r; + float g = texture(uImageTexture, uvCoord).g; + float b = texture(uImageTexture, bUV).b; + float a = texture(uImageTexture, uvCoord).a; + color = vec4(r, g, b, a); + } else { + color = texture(uImageTexture, uvCoord); + } + + if (uIsHlgInput != 0) { + color.rgb = hlgToLinear(color.rgb); + color.rgb = bt2020ToLinearSrgb(color.rgb); + color.rgb = linearToSrgb(color.rgb); + } + + if (uColorRecipeEnabled != 0) { + if (abs(uExposure) > 0.001) { + color.rgb = applyExposureInLinearSpace(color.rgb, uExposure); + color.rgb = sanitizeColor(color.rgb); + } + + float luma = getLuma(color.rgb); + float highlightMask = smoothstep(0.5, 1.0, luma); + float shadowMask = smoothstep(0.5, 0.0, luma); + float highlightFactor = (uHighlights > 0.0) ? (1.0 + uHighlights * 0.7) : (1.0 + uHighlights * 0.3); + color.rgb = mix(color.rgb, color.rgb * highlightFactor, highlightMask); + + vec3 shadowTarget = (uShadows > 0.0) ? (mix(color.rgb, vec3(luma), uShadows * 0.2) + (color.rgb * uShadows * 0.5)) : (color.rgb * (1.0 + uShadows * 0.5)); + color.rgb = mix(color.rgb, shadowTarget, shadowMask); + color.rgb = sanitizeColor(color.rgb); + + color.rgb = (color.rgb - 0.5) * uContrast + 0.5; + color.rgb = sanitizeColor(color.rgb); + + color.rgb = applyToneCurve(color.rgb, uToneToe, uToneShoulder, uTonePivot); + color.rgb = sanitizeColor(color.rgb); + + color.r += uTemperature * 0.1; + color.b -= uTemperature * 0.1; + color.g += uTint * 0.05; + color.rgb = sanitizeColor(color.rgb); + + float gray = getLuma(color.rgb); + color.rgb = mix(vec3(gray), color.rgb, uSaturation); + color.rgb = sanitizeColor(color.rgb); + + if (abs(uVibrance) > 0.001) { + color.rgb = applyOklchDensity(color.rgb, uVibrance); + color.rgb = sanitizeColor(color.rgb); + } + + color.rgb = applyPrimaryCalibration(color.rgb); + color.rgb = sanitizeColor(color.rgb); + + color.rgb = applyLchColorMixer(color.rgb); + color.rgb = sanitizeColor(color.rgb); + + if (uFade > 0.0) { + float fadeAmount = uFade * 0.3; + color.rgb = mix(color.rgb, vec3(0.5), fadeAmount); + color.rgb += fadeAmount * 0.1; + color.rgb = sanitizeColor(color.rgb); + } + + if (uBleachBypass > 0.0) { + float bleedLuma = getLuma(color.rgb); + vec3 desaturated = mix(color.rgb, vec3(bleedLuma), 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); + } + + if (abs(uVignette) > 0.0) { + vec2 center = vec2(0.5, 0.5); + float dist = distance(uvCoord, center); + float vignetteMask = smoothstep(0.8, 0.3, dist); + if (uVignette < 0.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); + } + } + + if (uFilmGrain > 0.0) { + float grainNoise = fract(sin(dot(uvCoord * 1000.0, vec2(12.9898, 78.233))) * 43758.5453); + grainNoise = (grainNoise - 0.5) * 2.0; + float grainLuma = getLuma(color.rgb); + float grainMask = 1.0 - abs(grainLuma - 0.5) * 2.0; + grainMask = grainMask * 0.5 + 0.5; + float grainStrength = uFilmGrain * 0.1 * grainMask; + color.rgb += grainNoise * grainStrength; + } + + if (uNoise > 0.001) { + vec2 seedOffset = vec2(fract(uNoiseSeed * 1.234), fract(uNoiseSeed * 3.456)); + vec2 noiseCoord = uvCoord * 800.0 + seedOffset * 100.0; + float lumNoise = fract(sin(dot(noiseCoord, vec2(12.9898, 78.233))) * 43758.5453); + lumNoise = (lumNoise - 0.5) * 2.0; + float colorNoiseR = fract(sin(dot(noiseCoord + vec2(1.1, 2.2), vec2(39.346, 11.135))) * 43758.5453); + float colorNoiseG = fract(sin(dot(noiseCoord + vec2(3.3, 4.4), vec2(73.156, 52.235))) * 43758.5453); + float colorNoiseB = fract(sin(dot(noiseCoord + vec2(5.5, 6.6), vec2(27.423, 83.136))) * 43758.5453); + vec3 colorNoise = (vec3(colorNoiseR, colorNoiseG, colorNoiseB) - 0.5) * 2.0; + float noiseLuma = getLuma(color.rgb); + float noiseMask = mix(0.5, 1.0, 1.0 - abs(noiseLuma - 0.5) * 1.5); + vec3 finalNoise = mix(vec3(lumNoise), mix(vec3(lumNoise), colorNoise, 0.7), 0.8); + color.rgb += finalNoise * uNoise * max(0.0, noiseMask); + } + + color.rgb = sanitizeColor(color.rgb); + } + + if (uCurveEnabled != 0) { + vec3 clamped = clamp(color.rgb, 0.0, 1.0); + float r = texture(uCurveTexture, vec2(clamped.r, 0.5)).r; + float g = texture(uCurveTexture, vec2(clamped.g, 0.5)).g; + float b = texture(uCurveTexture, vec2(clamped.b, 0.5)).b; + color.rgb = sanitizeColor(vec3(r, g, b)); + } + + if (uLutEnabled != 0 && uLutIntensity > 0.0) { + bool isP3 = (uInputColorSpace == 1); + vec3 linearInput = srgbToLinear(color.rgb); + if (isP3) { + linearInput = mat3(1.22486, -0.04205, -0.01974, -0.22471, 1.04192, -0.07865, 0.00000, 0.00013, 1.09837) * linearInput; + } + float effectiveLutIntensity = uLutIntensity * lutMaskWeight(uLutMaskType, linearInput); + vec3 colorSpaceRGB = applyLutColorSpace(linearInput, uLutColorSpace); + vec3 lutInColor = applyLutCurve(colorSpaceRGB, uLutCurve); + + float scale = (uLutSize - 1.0) / uLutSize; + float offset = 1.0 / (2.0 * uLutSize); + vec3 lutCoord = lutInColor * scale + offset; + vec4 lutColor = texture(uLutTexture, lutCoord); + + vec3 srgbColor = linearToSrgb(linearInput); + color.rgb = mix(srgbColor, lutColor.rgb, effectiveLutIntensity); + + if (isP3) { + vec3 linearSrgbOut = srgbToLinear(color.rgb); + color.rgb = linearToSrgb(mat3(0.875905, 0.035332, 0.016382, 0.122070, 0.964542, 0.063767, 0.002025, 0.000126, 0.919851) * linearSrgbOut); + } + } + + if (uSharpening > 0.0) { + vec3 inputColor = texture(uImageTexture, uvCoord).rgb; + float inputLuma = getLuma(inputColor); + float neighborsLuma = 0.0; + neighborsLuma += getLuma(texture(uImageTexture, uvCoord + vec2(-uTexelSize.x, 0.0)).rgb); + neighborsLuma += getLuma(texture(uImageTexture, uvCoord + vec2(uTexelSize.x, 0.0)).rgb); + neighborsLuma += getLuma(texture(uImageTexture, uvCoord + vec2(0.0, -uTexelSize.y)).rgb); + neighborsLuma += getLuma(texture(uImageTexture, uvCoord + vec2(0.0, uTexelSize.y)).rgb); + float blurLuma = neighborsLuma * 0.25; + float detail = inputLuma - blurLuma; + color.rgb += detail * uSharpening * 2.0; + } + + fragColor = clamp(color, 0.0, 1.0); + } + """.trimIndent() + } + + private var programId = 0 + + private val positionBuffer = floatArrayOf( + -1.0f, -1.0f, + 1.0f, -1.0f, + -1.0f, 1.0f, + 1.0f, 1.0f + ) + + private val texCoordBuffer = floatArrayOf( + 0.0f, 0.0f, + 1.0f, 0.0f, + 0.0f, 1.0f, + 1.0f, 1.0f + ) + + private var positionVbo = 0 + private var texCoordVbo = 0 + private var isGles3Context = false + + private var lutTextureId = 0 + private var curveTextureId = 0 + private var lastLutConfig: LutConfig? = null + private var lastRecipeParams: ColorRecipeParams? = null + + @Volatile + private var hasPendingUpdate = false + + init { + val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, VERTEX_SHADER) + val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, FRAGMENT_SHADER) + programId = GlUtils.linkProgram(vertexShader, fragmentShader) + positionVbo = GlUtils.createBuffer(positionBuffer) + texCoordVbo = GlUtils.createBuffer(texCoordBuffer) + + val version = GLES30.glGetString(GLES30.GL_VERSION) + isGles3Context = version != null && version.contains("OpenGL ES 3") + PLog.d("VideoLutShaderProgram", "OpenGL ES Version: $version, isGles3Context: $isGles3Context") + } + + private fun checkGlError(op: String) { + val error = GLES30.glGetError() + if (error != GLES30.GL_NO_ERROR) { + PLog.e("VideoLutShaderProgram", "GL Error after $op: 0x${Integer.toHexString(error)}") + } + } + + fun triggerUpdate() { + PLog.d("VideoLutShaderProgram", "triggerUpdate called, hasPendingUpdate: true") + hasPendingUpdate = true + } + + override fun configure(inputWidth: Int, inputHeight: Int): Size { + PLog.d("VideoLutShaderProgram", "configure called, inputWidth: $inputWidth, inputHeight: $inputHeight") + return Size(inputWidth, inputHeight) + } + + override fun drawFrame(inputTexId: Int, presentationTimeUs: Long) { +// PLog.v("VideoLutShaderProgram", "drawFrame called, inputTexId: $inputTexId, presentationTimeUs: $presentationTimeUs") + if (programId == 0) return + + val currentLutConfig = effect.lutConfig + val currentRecipeParams = effect.recipeParams + + // 检查并重新上传 LUT 纹理 + if (currentLutConfig != lastLutConfig || hasPendingUpdate) { + lastLutConfig = currentLutConfig + if (currentLutConfig != null) { + uploadLutTexture(currentLutConfig) + } else { + deleteLutTexture() + } + } + + // 检查并上传色彩曲线纹理 + val masterPts = currentRecipeParams?.masterCurvePoints + val redPts = currentRecipeParams?.redCurvePoints + val greenPts = currentRecipeParams?.greenCurvePoints + val bluePts = currentRecipeParams?.blueCurvePoints + val curveActive = masterPts != null || redPts != null || greenPts != null || bluePts != null + + if (currentRecipeParams != lastRecipeParams || hasPendingUpdate) { + lastRecipeParams = currentRecipeParams + if (curveActive) { + uploadCurveTexture(masterPts, redPts, greenPts, bluePts) + } else { + deleteCurveTexture() + } + hasPendingUpdate = false + } + + GLES30.glUseProgram(programId) + + var previousVao = 0 + if (isGles3Context) { + val params = IntArray(1) + GLES30.glGetIntegerv(GLES30.GL_VERTEX_ARRAY_BINDING, params, 0) + previousVao = params[0] + if (previousVao != 0) { + GLES30.glBindVertexArray(0) + } + } + + // 绑定位置属性 (VBO) + val aPositionLoc = GLES30.glGetAttribLocation(programId, "aPosition") + GLES30.glEnableVertexAttribArray(aPositionLoc) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, positionVbo) + GLES30.glVertexAttribPointer(aPositionLoc, 2, GLES30.GL_FLOAT, false, 0, 0) + + // 绑定纹理坐标属性 (VBO) + val aTexCoordLoc = GLES30.glGetAttribLocation(programId, "aTexCoord") + GLES30.glEnableVertexAttribArray(aTexCoordLoc) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, texCoordVbo) + GLES30.glVertexAttribPointer(aTexCoordLoc, 2, GLES30.GL_FLOAT, false, 0, 0) + + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0) + + // 绑定输入视频纹理 (GL_TEXTURE0) + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTexId) + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uImageTexture"), 0) + + // 绑定 3D LUT 纹理 (GL_TEXTURE1) + GLES30.glActiveTexture(GLES30.GL_TEXTURE1) + if (currentLutConfig != null && lutTextureId != 0) { + GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, lutTextureId) + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uLutTexture"), 1) + + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uLutSize"), currentLutConfig.size.toFloat()) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uLutIntensity"), currentRecipeParams?.lutIntensity ?: 1.0f) + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uLutEnabled"), 1) + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uLutMaskType"), 0) // 默认不加遮罩 + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uLutCurve"), currentLutConfig.curve.shaderId) + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uLutColorSpace"), currentLutConfig.colorSpace.ordinal) + } else { + GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, 0) + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uLutTexture"), 1) + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uLutEnabled"), 0) + } + + // 绑定色彩曲线纹理 (GL_TEXTURE3) + GLES30.glActiveTexture(GLES30.GL_TEXTURE3) + if (curveActive && curveTextureId != 0) { + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, curveTextureId) + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uCurveTexture"), 3) + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uCurveEnabled"), 1) + } else { + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTexId) + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uCurveTexture"), 3) + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uCurveEnabled"), 0) + } + + // 设置色彩配方 uniforms + val colorRecipeEnabled = currentRecipeParams != null && !currentRecipeParams.isDefault() + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uColorRecipeEnabled"), if (colorRecipeEnabled) 1 else 0) + + if (colorRecipeEnabled) { + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uExposure"), currentRecipeParams.exposure) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uContrast"), currentRecipeParams.contrast) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uSaturation"), currentRecipeParams.saturation) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uTemperature"), currentRecipeParams.temperature) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uTint"), currentRecipeParams.tint) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uFade"), currentRecipeParams.fade) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uVibrance"), currentRecipeParams.color) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uHighlights"), currentRecipeParams.highlights) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uShadows"), currentRecipeParams.shadows) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uToneToe"), currentRecipeParams.toneToe) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uToneShoulder"), currentRecipeParams.toneShoulder) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uTonePivot"), currentRecipeParams.tonePivot) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uFilmGrain"), currentRecipeParams.filmGrain) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uVignette"), currentRecipeParams.vignette) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uBleachBypass"), currentRecipeParams.bleachBypass) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uNoise"), currentRecipeParams.noise) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uNoiseSeed"), (presentationTimeUs % 10000000L) / 1000000f) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uLowRes"), currentRecipeParams.lowRes) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uAspectRatio"), 16f / 9f) + + // LCH 配方数组 + val lchHue = floatArrayOf( + currentRecipeParams.skinHue, currentRecipeParams.redHue, currentRecipeParams.orangeHue, + currentRecipeParams.yellowHue, currentRecipeParams.greenHue, currentRecipeParams.cyanHue, + currentRecipeParams.blueHue, currentRecipeParams.purpleHue, currentRecipeParams.magentaHue + ) + val lchChroma = floatArrayOf( + currentRecipeParams.skinChroma, currentRecipeParams.redChroma, currentRecipeParams.orangeChroma, + currentRecipeParams.yellowChroma, currentRecipeParams.greenChroma, currentRecipeParams.cyanChroma, + currentRecipeParams.blueChroma, currentRecipeParams.purpleChroma, currentRecipeParams.magentaChroma + ) + val lchLightness = floatArrayOf( + currentRecipeParams.skinLightness, currentRecipeParams.redLightness, currentRecipeParams.orangeLightness, + currentRecipeParams.yellowLightness, currentRecipeParams.greenLightness, currentRecipeParams.cyanLightness, + currentRecipeParams.blueLightness, currentRecipeParams.purpleLightness, currentRecipeParams.magentaLightness + ) + GLES30.glUniform1fv(GLES30.glGetUniformLocation(programId, "uLchHueAdjustments"), 9, lchHue, 0) + GLES30.glUniform1fv(GLES30.glGetUniformLocation(programId, "uLchChromaAdjustments"), 9, lchChroma, 0) + GLES30.glUniform1fv(GLES30.glGetUniformLocation(programId, "uLchLightnessAdjustments"), 9, lchLightness, 0) + + // Primary Calibration Matrix 3x3 (split into 3 row vectors to bypass Media3 mat3 uniform limitation) + val primaryCalibrationMatrix = CameraRawCalibrationMatrix.build(currentRecipeParams) + GLES30.glUniform3fv( + GLES30.glGetUniformLocation(programId, "uPrimaryCalibrationRow0"), + 1, floatArrayOf(primaryCalibrationMatrix[0], primaryCalibrationMatrix[3], primaryCalibrationMatrix[6]), 0 + ) + GLES30.glUniform3fv( + GLES30.glGetUniformLocation(programId, "uPrimaryCalibrationRow1"), + 1, floatArrayOf(primaryCalibrationMatrix[1], primaryCalibrationMatrix[4], primaryCalibrationMatrix[7]), 0 + ) + GLES30.glUniform3fv( + GLES30.glGetUniformLocation(programId, "uPrimaryCalibrationRow2"), + 1, floatArrayOf(primaryCalibrationMatrix[2], primaryCalibrationMatrix[5], primaryCalibrationMatrix[8]), 0 + ) + } + + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uInputColorSpace"), 0) // 默认 sRGB + GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uIsHlgInput"), 0) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uChromaticAberration"), 0f) + GLES30.glUniform1f(GLES30.glGetUniformLocation(programId, "uSharpening"), 0f) + + GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4) + checkGlError("glDrawArrays") + if (isGles3Context && previousVao != 0) { + GLES30.glBindVertexArray(previousVao) + } + } + + private fun uploadLutTexture(lutConfig: LutConfig) { + PLog.d("VideoLutShaderProgram", "uploadLutTexture starting. lutConfig: ${lutConfig.title}, size: ${lutConfig.size}, dataType: ${lutConfig.configDataType}") + try { + if (lutTextureId == 0) { + val textures = IntArray(1) + GLES30.glGenTextures(1, textures, 0) + lutTextureId = textures[0] + PLog.d("VideoLutShaderProgram", "Generated new 3D LUT texture ID: $lutTextureId") + } + + GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, lutTextureId) + checkGlError("glBindTexture 3D") + GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1) + + GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_WRAP_R, GLES30.GL_CLAMP_TO_EDGE) + + val buffer: java.nio.Buffer + val internalFormat: Int + val format: Int + val type: Int + + if (lutConfig.configDataType == LutConfig.CONFIG_DATA_TYPE_UINT16) { + buffer = lutConfig.toFloatBuffer() + internalFormat = GLES30.GL_RGB16F + format = GLES30.GL_RGB + type = GLES30.GL_FLOAT + PLog.d("VideoLutShaderProgram", "Prepared float buffer for LUT. size: ${buffer.capacity()}") + } else { + buffer = lutConfig.toByteBuffer() + internalFormat = GLES30.GL_RGB8 + format = GLES30.GL_RGB + type = GLES30.GL_UNSIGNED_BYTE + PLog.d("VideoLutShaderProgram", "Prepared byte buffer for LUT. size: ${buffer.capacity()}") + } + + GLES30.glTexImage3D( + GLES30.GL_TEXTURE_3D, 0, internalFormat, + lutConfig.size, lutConfig.size, lutConfig.size, + 0, format, type, buffer + ) + checkGlError("glTexImage3D") + + GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 4) + PLog.d("VideoLutShaderProgram", "uploadLutTexture completed successfully.") + } catch (e: Exception) { + PLog.e("VideoLutShaderProgram", "Failed to upload LUT texture!", e) + } + } + + private fun deleteLutTexture() { + if (lutTextureId != 0) { + GLES30.glDeleteTextures(1, intArrayOf(lutTextureId), 0) + lutTextureId = 0 + } + } + + private fun uploadCurveTexture( + master: FloatArray?, + red: FloatArray?, + green: FloatArray?, + blue: FloatArray? + ) { + if (curveTextureId == 0) { + val ids = IntArray(1) + GLES30.glGenTextures(1, ids, 0) + curveTextureId = ids[0] + } + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, curveTextureId) + 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) + + val curveBuffer = CurveUtils.buildCurveTextureBuffer(master, red, green, blue) + GLES30.glTexImage2D( + GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA8, 256, 1, 0, + GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, curveBuffer + ) + } + + private fun deleteCurveTexture() { + if (curveTextureId != 0) { + GLES30.glDeleteTextures(1, intArrayOf(curveTextureId), 0) + curveTextureId = 0 + } + } + + override fun release() { + super.release() + deleteLutTexture() + deleteCurveTexture() + if (positionVbo != 0) { + GLES30.glDeleteBuffers(1, intArrayOf(positionVbo), 0) + positionVbo = 0 + } + if (texCoordVbo != 0) { + GLES30.glDeleteBuffers(1, intArrayOf(texCoordVbo), 0) + texCoordVbo = 0 + } + if (programId != 0) { + GLES30.glDeleteProgram(programId) + programId = 0 + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryDetailScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryDetailScreen.kt index 990d3bfc..9bde68ad 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryDetailScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryDetailScreen.kt @@ -62,12 +62,15 @@ import androidx.compose.ui.viewinterop.AndroidView import androidx.core.view.isVisible import androidx.media3.ui.AspectRatioFrameLayout import coil.request.ImageRequest +import coil.compose.AsyncImage import com.hinnka.mycamera.hdr.HdrGainmapStrength import com.hinnka.mycamera.lut.creator.AiPhotoEvaluation +import com.hinnka.mycamera.lut.VideoLutEffect import com.hinnka.mycamera.ui.camera.autoRotate import com.hinnka.mycamera.ui.components.CustomSliderThinThumb import com.hinnka.mycamera.ui.components.PaymentDialog import com.hinnka.mycamera.utils.DeviceUtil +import com.hinnka.mycamera.utils.PLog import com.hinnka.mycamera.viewmodel.GalleryTab import kotlinx.coroutines.Dispatchers import me.saket.telephoto.zoomable.ZoomSpec @@ -104,6 +107,9 @@ fun GalleryDetailScreen( var showExportDialog by remember { mutableStateOf(false) } var isSaving by remember { mutableStateOf(false) } var isExportingDng by remember { mutableStateOf(false) } + val isVideoExporting = viewModel.isVideoExporting + val videoExportProgress = viewModel.videoExportProgress + var showVideoExportConfirmDialog by remember { mutableStateOf(false) } val isSharing by viewModel.isSharing.collectAsState() val isPurchased by viewModel.isPurchased.collectAsState() var showAiScoreSheet by remember { mutableStateOf(false) } @@ -396,7 +402,7 @@ fun GalleryDetailScreen( } // 编辑 - if (currentPhoto?.isImage == true) { + if (currentPhoto?.isImage == true || currentPhoto?.isVideo == true) { GalleryActionItem( icon = Icons.Default.Edit, text = stringResource(R.string.edit), @@ -515,7 +521,8 @@ fun GalleryDetailScreen( if (photo.isVideo) { VideoDetailPlayer( photo = photo, - isActive = page == pagerState.currentPage, + isActive = page == pagerState.currentPage && !viewModel.isEditing, + viewModel = viewModel, modifier = Modifier.fillMaxSize() ) } else { @@ -663,6 +670,7 @@ fun GalleryDetailScreen( currentPhoto?.let { isSaving = true viewModel.exportPhoto(it) { success -> + showMoreSheet = false isSaving = false if (success) { Toast.makeText(context, R.string.export_success, Toast.LENGTH_SHORT).show() @@ -687,6 +695,34 @@ fun GalleryDetailScreen( ) } + // 视频导出确认对话框 + if (showVideoExportConfirmDialog) { + AlertDialog( + onDismissRequest = { showVideoExportConfirmDialog = false }, + title = { Text(stringResource(R.string.export_video)) }, + text = { Text(stringResource(R.string.export_video_confirm)) }, + confirmButton = { + TextButton(onClick = { + showVideoExportConfirmDialog = false + currentPhoto?.let { photo -> + viewModel.exportVideo(photo) { success, _ -> + showMoreSheet = false + val msgRes = if (success) R.string.export_video_success else R.string.export_video_failed + Toast.makeText(context, msgRes, Toast.LENGTH_SHORT).show() + } + } + }) { + Text(stringResource(R.string.export_video)) + } + }, + dismissButton = { + TextButton(onClick = { showVideoExportConfirmDialog = false }) { + Text(stringResource(R.string.cancel)) + } + } + ) + } + // 照片信息对话框 if (showInfoDialog && currentPhoto != null) { AlertDialog( @@ -803,12 +839,23 @@ fun GalleryDetailScreen( text = stringResource(R.string.export), isLoading = isSaving, onClick = { - showMoreSheet = false showExportDialog = true } ) } + // 视频导出按钮(仅视频) + if (currentPhoto.isVideo) { + GalleryActionItem( + icon = Icons.Default.Output, + text = if (isVideoExporting && videoExportProgress > 0) "$videoExportProgress%" else stringResource(R.string.export), + isLoading = isVideoExporting, + onClick = { + showVideoExportConfirmDialog = true + } + ) + } + // DNG if (isCurrentRawPhoto) { GalleryActionItem( @@ -1308,46 +1355,143 @@ private fun Context.findActivity(): Activity? { private fun VideoDetailPlayer( photo: MediaData, isActive: Boolean, + viewModel: GalleryViewModel, modifier: Modifier = Modifier ) { val context = LocalContext.current val mediaUri = remember(photo.id, photo.uri, photo.sourceUri) { photo.sourceUri ?: photo.uri } - val exoPlayer = remember(photo.id, mediaUri) { + + PLog.d("VideoDetailPlayer", "VideoDetailPlayer recomposing/initializing. photoId: ${photo.id}, isActive: $isActive, mediaUri: $mediaUri") + + val contentRepository = remember { + com.hinnka.mycamera.data.ContentRepository.getInstance(context) + } + + var lutConfig by remember { mutableStateOf(null) } + var recipeParams by remember { mutableStateOf(null) } + val refreshKey = viewModel.photoRefreshKeys[photo.id] ?: 0L + + LaunchedEffect(photo.id, refreshKey) { + withContext(Dispatchers.IO) { + PLog.d("VideoDetailPlayer", "Loading video metadata from DB.") + val metadata = com.hinnka.mycamera.gallery.GalleryManager.loadMetadata(context, photo.id) ?: photo.metadata + val lutId = metadata?.lutId + val params = metadata?.colorRecipeParams + PLog.d("VideoDetailPlayer", "Metadata loaded. lutId: $lutId, recipeEnabled: ${params != null}") + + val config = if (lutId != null) { + contentRepository.lutManager.loadLut(lutId) + } else { + null + } + + withContext(Dispatchers.Main) { + lutConfig = config + recipeParams = params + } + } + } + + // Maintain the video LUT effect + val videoLutEffect = remember { + PLog.d("VideoDetailPlayer", "Instantiating new VideoLutEffect.") + VideoLutEffect(lutConfig, recipeParams) + } + + // Update effect parameters dynamically on the GL pipeline without reconstruction + LaunchedEffect(lutConfig, recipeParams) { + PLog.d("VideoDetailPlayer", "Updating VideoLutEffect params. lut: ${lutConfig?.title}, recipe: ${recipeParams != null}") + videoLutEffect.update(lutConfig, recipeParams) + } + + val exoPlayer = remember(photo.id, mediaUri, isActive) { + if (!isActive) return@remember null + PLog.d("VideoDetailPlayer", "Creating ExoPlayer for detail video.") ExoPlayer.Builder(context).build().apply { - setMediaItem(MediaItem.fromUri(mediaUri)) repeatMode = Player.REPEAT_MODE_OFF - prepare() - playWhenReady = true + setVideoEffects(listOf(videoLutEffect)) + + addListener(object : Player.Listener { + override fun onPlaybackStateChanged(state: Int) { + PLog.d("VideoDetailPlayer", "ExoPlayer state changed: $state") + } + override fun onPlayerError(error: androidx.media3.common.PlaybackException) { + PLog.e("VideoDetailPlayer", "ExoPlayer encountered error!", error) + } + }) } } DisposableEffect(exoPlayer) { - onDispose { exoPlayer.release() } - } - - LaunchedEffect(exoPlayer, isActive) { - exoPlayer.playWhenReady = isActive - if (!isActive) { - exoPlayer.pause() + onDispose { + if (exoPlayer != null) { + PLog.d("VideoDetailPlayer", "Disposing ExoPlayer.") + exoPlayer.release() + } } } - AndroidView( - factory = { - LayoutInflater.from(context).inflate(R.layout.view_motion_photo_player, null) as PlayerView - }, - update = { - it.player = exoPlayer - it.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT - it.useController = true - it.controllerAutoShow = false - it.setShowBuffering(PlayerView.SHOW_BUFFERING_NEVER) - it.isVisible = true - }, - modifier = modifier.autoRotate(matchParentSize = true) - ) + LaunchedEffect(exoPlayer, isActive) { + PLog.d("VideoDetailPlayer", "VideoDetailPlayer isActive changed: $isActive, player: $exoPlayer") + if (exoPlayer != null && isActive) { + delay(150) // Wait for transitions to complete and EGL surface to be fully ready + PLog.d("VideoDetailPlayer", "Preparing and starting ExoPlayer.") + exoPlayer.setMediaItem(MediaItem.fromUri(mediaUri)) + exoPlayer.prepare() + exoPlayer.playWhenReady = true + } + } + + if (exoPlayer != null) { + AndroidView( + factory = { + PLog.d("VideoDetailPlayer", "Creating PlayerView factory.") + LayoutInflater.from(context).inflate(R.layout.view_motion_photo_player, null) as PlayerView + }, + update = { + PLog.d("VideoDetailPlayer", "Updating PlayerView with player.") + it.player = exoPlayer + it.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT + it.useController = true + it.controllerAutoShow = false + it.setShowBuffering(PlayerView.SHOW_BUFFERING_NEVER) + it.isVisible = true + }, + modifier = modifier.autoRotate(matchParentSize = true) + ) + } else { + // Show video thumbnail with a play icon when player is not active + Box( + modifier = modifier.autoRotate(matchParentSize = true), + contentAlignment = Alignment.Center + ) { + val transformation = remember(photo) { + viewModel.getPhotoTransformation(photo) + } + AsyncImage( + model = ImageRequest.Builder(context) + .data(photo.thumbnailUri) + .crossfade(true) + .apply { + if (transformation != null) { + transformations(transformation) + } + } + .build(), + contentDescription = photo.displayName, + contentScale = ContentScale.Fit, + modifier = Modifier.fillMaxSize() + ) + Icon( + imageVector = Icons.Default.PlayArrow, + contentDescription = null, + tint = Color.White.copy(alpha = 0.8f), + modifier = Modifier.size(64.dp) + ) + } + } } /** diff --git a/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt similarity index 81% rename from app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt rename to app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt index a31df591..58db607a 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt @@ -30,9 +30,9 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.FileDownload import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Tune -import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment @@ -55,7 +55,6 @@ import com.hinnka.mycamera.R import me.saket.telephoto.zoomable.coil.ZoomableAsyncImage import me.saket.telephoto.zoomable.rememberZoomableImageState import me.saket.telephoto.zoomable.rememberZoomableState -import com.hinnka.mycamera.frame.TextType import com.hinnka.mycamera.gallery.MediaData import com.hinnka.mycamera.model.ColorRecipeParams import com.hinnka.mycamera.ui.camera.LutEditBottomSheet @@ -76,9 +75,19 @@ import kotlinx.coroutines.flow.conflate import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.filter import kotlinx.coroutines.withContext +import kotlinx.coroutines.delay import me.saket.telephoto.zoomable.ZoomSpec -import java.text.SimpleDateFormat -import java.util.* + +import androidx.compose.ui.viewinterop.AndroidView +import android.view.LayoutInflater +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.common.MediaItem +import androidx.media3.common.Player +import androidx.media3.ui.PlayerView +import androidx.media3.ui.AspectRatioFrameLayout +import com.hinnka.mycamera.lut.VideoLutEffect +import com.hinnka.mycamera.lut.LutConfig +import com.hinnka.mycamera.ui.camera.autoRotate private data class PreviewRenderSignature( val photoId: String, @@ -115,7 +124,7 @@ private data class PreviewRenderSignature( @SuppressLint("LocalContextGetResourceValueCall") @OptIn(ExperimentalMaterial3Api::class, FlowPreview::class) @Composable -fun PhotoEditScreen( +fun GalleryEditScreen( viewModel: GalleryViewModel, cameraViewModel: CameraViewModel, onBack: () -> Unit, @@ -303,6 +312,7 @@ fun PhotoEditScreen( LaunchedEffect(currentPhoto, refreshKey) { val photo = currentPhoto ?: return@LaunchedEffect + if (photo.isVideo) return@LaunchedEffect snapshotFlow { currentPreviewSignature() } @@ -315,6 +325,7 @@ fun PhotoEditScreen( LaunchedEffect(currentPhoto, refreshKey) { val photo = currentPhoto ?: return@LaunchedEffect + if (photo.isVideo) return@LaunchedEffect snapshotFlow { currentPreviewSignature() } @@ -648,15 +659,24 @@ fun PhotoEditScreen( contentAlignment = Alignment.Center ) { // 显示预览 - ZoomableEditImage( - previewBitmap = previewBitmap, - isLutEditing = isLutEditSheetVisible || isBaselineLutEditSheetVisible, - contentDescription = stringResource(R.string.edit), - onZoomChange = { - isZoomed = it - }, - modifier = Modifier.fillMaxSize() - ) + if (currentPhoto.isVideo) { + VideoEditPlayer( + photo = currentPhoto, + lutConfig = editLutConfig, + recipeParams = if (showOrigin) null else (previewRecipeParamsOverride ?: editPhotoRecipeParams ?: editLutRecipeParams), + modifier = Modifier.fillMaxSize() + ) + } else { + ZoomableEditImage( + previewBitmap = previewBitmap, + isLutEditing = isLutEditSheetVisible || isBaselineLutEditSheetVisible, + contentDescription = stringResource(R.string.edit), + onZoomChange = { + isZoomed = it + }, + modifier = Modifier.fillMaxSize() + ) + } // 只有在裁剪标签页才显示叠加层并且只能操作裁剪层 if (editTab == 3 && previewBitmap != null) { @@ -807,11 +827,13 @@ fun PhotoEditScreen( onClick = { editTab = 2 } ) } - TabItem( - title = stringResource(R.string.crop), - isSelected = editTab == 3, - onClick = { editTab = 3 } - ) + if (!currentPhoto.isVideo) { + TabItem( + title = stringResource(R.string.crop), + isSelected = editTab == 3, + onClick = { editTab = 3 } + ) + } } Column(modifier = Modifier.heightIn(max = 550.dp).verticalScroll(rememberScrollState())) { when (editTab) { @@ -883,149 +905,153 @@ fun PhotoEditScreen( categoryOrder = categoryOrder ) - Spacer(modifier = Modifier.height(16.dp)) + if (!currentPhoto.isVideo) { + Spacer(modifier = Modifier.height(16.dp)) - // 边框水印选择器 - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text( - text = stringResource(R.string.frame), - color = Color.White, - fontSize = 16.sp - ) + // 边框水印选择器 + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource(R.string.frame), + color = Color.White, + fontSize = 16.sp + ) - if (editFrameId != null) { - val currentFrame = availableFrames.find { it.id == editFrameId } - if (currentFrame?.isEditable == true) { - Row( - modifier = Modifier - .clip(RoundedCornerShape(16.dp)) - .background(Color.White.copy(alpha = 0.1f)) - .clickable { onOpenFrameEditor(currentFrame.id) } - .padding(horizontal = 10.dp, vertical = 4.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(4.dp) - ) { - Icon( - imageVector = Icons.Default.Tune, - contentDescription = null, - tint = Color(0xFFFFD700), - modifier = Modifier.size(14.dp) - ) - Text( - text = stringResource(R.string.edit), - color = Color.White, - fontSize = 11.sp - ) + if (editFrameId != null) { + val currentFrame = availableFrames.find { it.id == editFrameId } + if (currentFrame?.isEditable == true) { + Row( + modifier = Modifier + .clip(RoundedCornerShape(16.dp)) + .background(Color.White.copy(alpha = 0.1f)) + .clickable { onOpenFrameEditor(currentFrame.id) } + .padding(horizontal = 10.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Icon( + imageVector = Icons.Default.Tune, + contentDescription = null, + tint = Color(0xFFFFD700), + modifier = Modifier.size(14.dp) + ) + Text( + text = stringResource(R.string.edit), + color = Color.White, + fontSize = 11.sp + ) + } } } } - } - Spacer(modifier = Modifier.height(8.dp)) + Spacer(modifier = Modifier.height(8.dp)) - LazyRow( - horizontalArrangement = Arrangement.spacedBy(12.dp), - state = frameScrollState - ) { - // 无边框选项 - item { - FrameOption( - name = stringResource(R.string.none), - isSelected = editFrameId == null, - isCustom = false, // 无边框不是自定义 - onClick = { viewModel.setEditFrame(null) } - ) - } + LazyRow( + horizontalArrangement = Arrangement.spacedBy(12.dp), + state = frameScrollState + ) { + // 无边框选项 + item { + FrameOption( + name = stringResource(R.string.none), + isSelected = editFrameId == null, + isCustom = false, // 无边框不是自定义 + onClick = { viewModel.setEditFrame(null) } + ) + } - // 边框选项 - items(availableFrames) { frame -> - FrameOption( - name = frame.name, - isSelected = editFrameId == frame.id, - isCustom = !frame.isBuiltIn, // 添加自定义标识 - isEditable = frame.isEditable, - onClick = { - if (editFrameId == frame.id) { - if (frame.isEditable) { - onOpenFrameEditor(frame.id) + // 边框选项 + items(availableFrames) { frame -> + FrameOption( + name = frame.name, + isSelected = editFrameId == frame.id, + isCustom = !frame.isBuiltIn, // 添加自定义标识 + isEditable = frame.isEditable, + onClick = { + if (editFrameId == frame.id) { + if (frame.isEditable) { + onOpenFrameEditor(frame.id) + } + } else { + viewModel.setEditFrame(frame.id) } - } else { - viewModel.setEditFrame(frame.id) } - } - ) + ) + } } } } 1 -> { Spacer(modifier = Modifier.height(16.dp)) - val isDnCNNDenoising by viewModel.isAiDenoising.collectAsState() - val dnCNNProgress by viewModel.aiDenoiseProgress.collectAsState() + if (!currentPhoto.isVideo) { + val isDnCNNDenoising by viewModel.isAiDenoising.collectAsState() + val dnCNNProgress by viewModel.aiDenoiseProgress.collectAsState() - SliderSettingItem( - title = stringResource(R.string.ai_denoise_title), - description = if (isDnCNNDenoising) stringResource( - R.string.ai_denoise_processing, - dnCNNProgress * 100 - ) else stringResource(R.string.ai_denoise_description), - value = editAiDenoiseStrength, - valueRange = 0f..1f, - onValueChange = { viewModel.setAiDenoiseStrength(it) }, - onValueChangeFinished = { - if (isDnCNNDenoising) return@SliderSettingItem - if (editAiDenoiseStrength > 0.01f) { - viewModel.applyDnCNNDenoise( - photo = currentPhoto, - strength = editAiDenoiseStrength, - onComplete = { success -> - if (!success) { - Toast.makeText( - context, - context.getString(R.string.ai_denoise_failed), - Toast.LENGTH_SHORT - ).show() + SliderSettingItem( + title = stringResource(R.string.ai_denoise_title), + description = if (isDnCNNDenoising) stringResource( + R.string.ai_denoise_processing, + dnCNNProgress * 100 + ) else stringResource(R.string.ai_denoise_description), + value = editAiDenoiseStrength, + valueRange = 0f..1f, + onValueChange = { viewModel.setAiDenoiseStrength(it) }, + onValueChangeFinished = { + if (isDnCNNDenoising) return@SliderSettingItem + if (editAiDenoiseStrength > 0.01f) { + viewModel.applyDnCNNDenoise( + photo = currentPhoto, + strength = editAiDenoiseStrength, + onComplete = { success -> + if (!success) { + Toast.makeText( + context, + context.getString(R.string.ai_denoise_failed), + Toast.LENGTH_SHORT + ).show() + } } - } - ) - } else { - viewModel.resetDnCNNDenoise( - photo = currentPhoto, - onComplete = { success -> - if (!success) { - Toast.makeText( - context, - context.getString(R.string.ai_denoise_failed), - Toast.LENGTH_SHORT - ).show() + ) + } else { + viewModel.resetDnCNNDenoise( + photo = currentPhoto, + onComplete = { success -> + if (!success) { + Toast.makeText( + context, + context.getString(R.string.ai_denoise_failed), + Toast.LENGTH_SHORT + ).show() + } } - } - ) + ) + } } - } - ) - Spacer(modifier = Modifier.height(8.dp)) - // 细节处理调整 (锐化, 降噪, 杂色降噪) - val aperture = editComputationalAperture - SliderSettingItem( - title = stringResource(R.string.virtual_aperture), - value = editComputationalAperture ?: 2.8f, - valueRange = 1.0f..16.0f, - onValueChange = { viewModel.setComputationalAperture(it) }, - onValueChangeFinished = { }, - toggleValue = aperture != null && aperture > 0f, - onToggleChange = { checked -> - if (checked) { - viewModel.setComputationalAperture(2.8f) - } else { - viewModel.setComputationalAperture(null) + ) + Spacer(modifier = Modifier.height(8.dp)) + // 细节处理调整 (锐化, 降噪, 杂色降噪) + val aperture = editComputationalAperture + SliderSettingItem( + title = stringResource(R.string.virtual_aperture), + value = editComputationalAperture ?: 2.8f, + valueRange = 1.0f..16.0f, + onValueChange = { viewModel.setComputationalAperture(it) }, + onValueChangeFinished = { }, + toggleValue = aperture != null && aperture > 0f, + onToggleChange = { checked -> + if (checked) { + viewModel.setComputationalAperture(2.8f) + } else { + viewModel.setComputationalAperture(null) + } } - } - ) + ) + } SliderSettingItem( title = stringResource(R.string.settings_sharpening), value = editSharpening, @@ -1127,15 +1153,17 @@ fun PhotoEditScreen( ) } 3 -> { - // 裁剪编辑 - val availablePhotoAspectRatios by cameraViewModel.availablePhotoAspectRatios.collectAsState() - CropEditPanel( - selectedOption = editCropAspectOption, - onOptionSelected = { viewModel.setCropAspectOption(it) }, - availableRatios = availablePhotoAspectRatios, - imageWidth = previewBitmap?.width ?: 1, - imageHeight = previewBitmap?.height ?: 1 - ) + if (!currentPhoto.isVideo) { + // 裁剪编辑 + val availablePhotoAspectRatios by cameraViewModel.availablePhotoAspectRatios.collectAsState() + CropEditPanel( + selectedOption = editCropAspectOption, + onOptionSelected = { viewModel.setCropAspectOption(it) }, + availableRatios = availablePhotoAspectRatios, + imageWidth = previewBitmap?.width ?: 1, + imageHeight = previewBitmap?.height ?: 1 + ) + } } } } @@ -1469,3 +1497,84 @@ private fun SegmentedControl( } } } + +@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +@Composable +private fun VideoEditPlayer( + photo: MediaData, + lutConfig: LutConfig?, + recipeParams: ColorRecipeParams?, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + val mediaUri = remember(photo.id, photo.uri, photo.sourceUri) { + photo.sourceUri ?: photo.uri + } + + PLog.d("VideoEditPlayer", "VideoEditPlayer composable recomposing/initializing. photoId: ${photo.id}, mediaUri: $mediaUri") + + var isPlayerActive by remember { mutableStateOf(false) } + LaunchedEffect(photo.id) { + delay(150) // Wait for the transitions to complete and EGL context release + isPlayerActive = true + } + + val videoLutEffect = remember { + PLog.d("VideoEditPlayer", "Instantiating new VideoLutEffect.") + VideoLutEffect(lutConfig, recipeParams) + } + + LaunchedEffect(lutConfig, recipeParams) { + PLog.d("VideoEditPlayer", "Updating VideoLutEffect with lutConfig: ${lutConfig?.title}, recipeParams: ${recipeParams != null}") + videoLutEffect.update(lutConfig, recipeParams) + } + + val exoPlayer = remember(photo.id, mediaUri, isPlayerActive) { + if (!isPlayerActive) return@remember null + PLog.d("VideoEditPlayer", "Re-creating loopable ExoPlayer instance for video preview.") + ExoPlayer.Builder(context).build().apply { + setMediaItem(MediaItem.fromUri(mediaUri)) + repeatMode = Player.REPEAT_MODE_ONE + setVideoEffects(listOf(videoLutEffect)) + prepare() + playWhenReady = true + + addListener(object : Player.Listener { + override fun onPlaybackStateChanged(state: Int) { + PLog.d("VideoEditPlayer", "ExoPlayer state changed: $state") + } + override fun onPlayerError(error: androidx.media3.common.PlaybackException) { + PLog.e("VideoEditPlayer", "ExoPlayer encountered playback error!", error) + } + }) + } + } + + DisposableEffect(exoPlayer) { + onDispose { + if (exoPlayer != null) { + PLog.d("VideoEditPlayer", "Disposing loopable ExoPlayer.") + exoPlayer.release() + } + } + } + + if (exoPlayer != null) { + AndroidView( + factory = { + PLog.d("VideoEditPlayer", "Creating PlayerView factory.") + LayoutInflater.from(context).inflate(R.layout.view_motion_photo_player, null) as PlayerView + }, + update = { + PLog.d("VideoEditPlayer", "Updating PlayerView with ExoPlayer.") + it.player = exoPlayer + it.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT + it.useController = false + it.visibility = android.view.View.VISIBLE + }, + modifier = modifier.autoRotate(matchParentSize = true) + ) + } else { + Spacer(modifier = modifier.fillMaxSize()) + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt index 06e9be08..7f989a13 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt @@ -28,6 +28,7 @@ import com.hinnka.mycamera.lut.BaselineColorCorrectionTarget import com.hinnka.mycamera.lut.LutConfig import com.hinnka.mycamera.lut.LutInfo import com.hinnka.mycamera.lut.PhotoTransformation +import com.hinnka.mycamera.lut.exportVideoWithEffects import com.hinnka.mycamera.lut.creator.OpenAIApiClient import com.hinnka.mycamera.model.ColorRecipeParams import com.hinnka.mycamera.raw.DcpInfo @@ -173,12 +174,18 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) private val _isSharing = MutableStateFlow(false) val isSharing: StateFlow = _isSharing.asStateFlow() - // 导出状态 + // 导出状态(照片批量导出) private val _isExporting = MutableStateFlow(false) val isExporting: StateFlow = _isExporting.asStateFlow() var exportProgress by mutableStateOf(0 to 0) private set + // 视频导出状态 + var isVideoExporting by mutableStateOf(false) + private set + var videoExportProgress by mutableStateOf(0) + private set + // 多选模式 var isSelectionMode by mutableStateOf(false) private set @@ -1556,7 +1563,6 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) */ fun enterEditMode() { val targetPhoto = getCurrentPhoto() ?: return - if (targetPhoto.isVideo) return if (currentMediaMetadata == null || currentPhotoMetadataId != targetPhoto.id) { val context = getApplication() @@ -1581,46 +1587,52 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) currentMediaMetadata?.let { metadata -> editLutId.value = metadata.lutId editFrameId.value = metadata.frameId - editRawDcpId.value = metadata.rawDcpId - editRawBaselineLutId.value = metadata.baselineLutId - restoreCropEditState(targetPhoto, metadata) editPhotoRecipeParams.value = metadata.colorRecipeParams - // 智能初始化:导入的照片默认值为 0,App 拍摄的则回退到当前全局配置 - editSharpening.value = - metadata.sharpening ?: (if (metadata.isImported) 0f else sharpening.value) - editNoiseReduction.value = - metadata.noiseReduction ?: (if (metadata.isImported) 0f else noiseReduction.value) - editChromaNoiseReduction.value = - metadata.chromaNoiseReduction - ?: (if (metadata.isImported) 0f else chromaNoiseReduction.value) - editRawDenoise.value = metadata.rawDenoiseValue ?: 0f - editRawExposureCompensation.value = metadata.rawExposureCompensation ?: 0f - editRawAutoExposure.value = metadata.rawAutoExposure ?: true - editRawBlackPointCorrection.value = metadata.rawBlackPointCorrection ?: 0f - editRawWhitePointCorrection.value = metadata.rawWhitePointCorrection ?: 0f - editRawDROMode.value = RawProcessingPreferences.DROMode.fromPersistedName(metadata.droMode).name - editComputationalAperture.value = metadata.computationalAperture - editFocusPointX.value = metadata.focusPointX - editFocusPointY.value = metadata.focusPointY + + if (!targetPhoto.isVideo) { + editRawDcpId.value = metadata.rawDcpId + editRawBaselineLutId.value = metadata.baselineLutId + restoreCropEditState(targetPhoto, metadata) + // 智能初始化:导入的照片默认值为 0,App 拍摄的则回退到当前全局配置 + editSharpening.value = + metadata.sharpening ?: (if (metadata.isImported) 0f else sharpening.value) + editNoiseReduction.value = + metadata.noiseReduction ?: (if (metadata.isImported) 0f else noiseReduction.value) + editChromaNoiseReduction.value = + metadata.chromaNoiseReduction + ?: (if (metadata.isImported) 0f else chromaNoiseReduction.value) + editRawDenoise.value = metadata.rawDenoiseValue ?: 0f + editRawExposureCompensation.value = metadata.rawExposureCompensation ?: 0f + editRawAutoExposure.value = metadata.rawAutoExposure ?: true + editRawBlackPointCorrection.value = metadata.rawBlackPointCorrection ?: 0f + editRawWhitePointCorrection.value = metadata.rawWhitePointCorrection ?: 0f + editRawDROMode.value = RawProcessingPreferences.DROMode.fromPersistedName(metadata.droMode).name + editComputationalAperture.value = metadata.computationalAperture + editFocusPointX.value = metadata.focusPointX + editFocusPointY.value = metadata.focusPointY + } } ?: run { editLutId.value = null editFrameId.value = null - // 这里一般是本 App 预览或拍摄进入,保持跟随全局 - editSharpening.value = sharpening.value - editNoiseReduction.value = noiseReduction.value - editChromaNoiseReduction.value = chromaNoiseReduction.value - editRawDenoise.value = 0.2f - editRawExposureCompensation.value = 0f - editRawAutoExposure.value = true - editRawBlackPointCorrection.value = 0f - editRawWhitePointCorrection.value = 0f - editRawDROMode.value = "OFF" - editRawDcpId.value = null - editRawBaselineLutId.value = null - editComputationalAperture.value = null - editFocusPointX.value = null - editFocusPointY.value = null - restoreCropEditState(targetPhoto, null) + + if (!targetPhoto.isVideo) { + // 这里一般是本 App 预览或拍摄进入,保持跟随全局 + editSharpening.value = sharpening.value + editNoiseReduction.value = noiseReduction.value + editChromaNoiseReduction.value = chromaNoiseReduction.value + editRawDenoise.value = 0.2f + editRawExposureCompensation.value = 0f + editRawAutoExposure.value = true + editRawBlackPointCorrection.value = 0f + editRawWhitePointCorrection.value = 0f + editRawDROMode.value = "OFF" + editRawDcpId.value = null + editRawBaselineLutId.value = null + editComputationalAperture.value = null + editFocusPointX.value = null + editFocusPointY.value = null + restoreCropEditState(targetPhoto, null) + } } // 加载当前编辑的 LUT 配置 @@ -2503,6 +2515,80 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) } } + /** + * 导出视频:使用 Media3 Transformer 将 LUT / 色彩配方效果烘焙到视频文件并保存到系统相册。 + * 导出不修改原始视频,结果保存在 Movies/PhotonCamera/ 目录。 + */ + @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) + fun exportVideo( + photo: MediaData, + onComplete: (success: Boolean, exportedUri: android.net.Uri?) -> Unit = { _, _ -> } + ) { + if (!photo.isVideo) { + onComplete(false, null) + return + } + if (isVideoExporting) return + + viewModelScope.launch { + isVideoExporting = true + videoExportProgress = 0 + try { + val context = getApplication() + + // 获取最新元数据(包含 lutId 和 colorRecipeParams) + val metadata = GalleryManager.loadMetadata(context, photo.id) ?: photo.metadata + + // 加载 LUT 配置 + val lutId = metadata?.lutId + val lutConfig = lutId?.let { + contentRepository.lutManager.loadLut(it) + } + + // 获取色彩配方 + val recipeParams = metadata?.colorRecipeParams + + // 视频输入 URI:优先使用 sourceUri(PhotonCamera 录制的视频),否则使用 uri + val inputUri = photo.sourceUri ?: photo.uri + + // 生成输出文件名(基于原始文件名加 _edit 后缀) + val baseName = photo.displayName + .substringBeforeLast(".") + .ifBlank { "PhotonCamera_video" } + val lutSuffix = lutId?.let { + contentRepository.lutManager.getLutInfo(it)?.getName() ?: "" + }?.let { if (it.isNotEmpty()) ".$it" else "" } ?: "" + val outputName = "${baseName}${lutSuffix}_edit" + + val resultUri = exportVideoWithEffects( + context = context, + inputUri = inputUri, + lutConfig = lutConfig, + recipeParams = recipeParams, + outputDisplayName = outputName, + onProgress = { progress -> + videoExportProgress = progress + } + ) + + // 记录导出 URI 到元数据 + if (resultUri != null) { + GalleryManager.updateMetadata(context, photo.id) { current -> + current.copy(exportedUris = current.exportedUris + resultUri.toString()) + } + } + + onComplete(resultUri != null, resultUri) + } catch (e: Exception) { + PLog.e(TAG, "exportVideo failed", e) + onComplete(false, null) + } finally { + isVideoExporting = false + videoExportProgress = 0 + } + } + } + fun exportDng( photo: MediaData, onComplete: (Boolean) -> Unit = {} diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 992d1648..ae965c90 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -112,6 +112,11 @@ DNG 导出成功 DNG 导出失败 导出所有连拍照片吗? + 导出视频 + 将效果烘焙到视频并保存到相册?根据视频时长可能需要一些时间,原始视频不会被修改。 + 视频导出成功 + 视频导出失败 + 正在导出视频… %d%% 编辑 刷新预览失败 全选 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 88e99564..eb13dc74 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -112,6 +112,11 @@ DNG exported successfully Failed to export DNG Export all burst photos? + Export Video + Bake effects into video and save to gallery? This may take a while depending on video length. The original video will not be changed. + Video exported successfully + Failed to export video + Exporting video… %d%% Edit Refresh Preview refreshed diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7a88815e..e66e29c0 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -30,6 +30,8 @@ ksp = "2.3.6" androidx-recyclerview = { module = "androidx.recyclerview:recyclerview", version.ref = "recyclerview" } media3-exoplayer = { group = "androidx.media3", name = "media3-exoplayer", version.ref = "media3" } media3-ui = { group = "androidx.media3", name = "media3-ui", version.ref = "media3" } +media3-effect = { group = "androidx.media3", name = "media3-effect", version.ref = "media3" } +media3-transformer = { group = "androidx.media3", name = "media3-transformer", version.ref = "media3" } google-billing = { group = "com.android.billingclient", name = "billing", version.ref = "billing" } google-billing-ktx = { group = "com.android.billingclient", name = "billing-ktx", version.ref = "billing" }