feat: restrict depth model to Depth Anything 3 and optimize bokeh performance

This commit is contained in:
zhoubinjia committed 2026-11-11 18:01:17 +08:00
1 parent f323fcd952
commit 60f5bb0470
23 files changed
+827 -703

No files matched your search

@@ -140,6 +140,9 @@ object GalleryManager {
private const val AI_DENOISE_FILE = "ai_denoise.jpg"
private const val THUMBNAIL_FILE = "thumbnail.jpg"
private const val BOKEH_FILE = "bokeh.jpg"
private const val DEPTH_CACHE_FILE = "depthmap.phdp"
/** 8-bit depth PNG of versions before the float cache; never read any more. */
private const val LEGACY_DEPTH_CACHE_FILE = "depthmap.png"
private const val DETAIL_HDR_FILE = "detail_hdr.jpg"
private const val MULTIPLE_EXPOSURE_DIR = "multiple_exposure_sessions"
private const val MULTIPLE_EXPOSURE_PREVIEW_FILE = "preview.jpg"
@@ -631,12 +634,24 @@ object GalleryManager {
return File(getPhotoDir(context, photoId), AI_DENOISE_FILE)
}
fun getDepthFile(context: Context, photoId: String): File {
return File(getPhotoDir(context, photoId), "depthmap.png")
fun getFloatDepthFile(context: Context, photoId: String): File {
return File(getPhotoDir(context, photoId), DEPTH_CACHE_FILE)
}
fun getFloatDepthFile(context: Context, photoId: String): File {
return File(getPhotoDir(context, photoId), "depthmap.phdp")
/**
* Removes every photo's former 8-bit depth cache and each float depth cache for which
* [isStale] holds. Returns the number of removed files.
*/
fun removeDepthCaches(context: Context, isStale: (File) -> Boolean): Int {
var removed = 0
getPhotosBaseDir(context).listFiles()?.forEach { photoDir ->
if (!photoDir.isDirectory) return@forEach
val legacy = File(photoDir, LEGACY_DEPTH_CACHE_FILE)
if (legacy.exists() && legacy.delete()) removed++
val cache = File(photoDir, DEPTH_CACHE_FILE)
if (cache.exists() && isStale(cache) && cache.delete()) removed++
}
return removed
}
fun getThumbnailFile(context: Context, photoId: String): File {
@@ -19,52 +19,51 @@ import java.nio.MappedByteBuffer
import java.nio.channels.FileChannel
/**
* Runs the installed monocular depth model and returns a normalized disparity map
* (larger is nearer) in the orientation of the input image.
* Runs Depth Anything 3 Small (see [DepthModelManager]) and returns a normalized disparity
* map (larger is nearer) in the orientation of the input image.
*
* The default model (Depth Anything 3 Small, see [DepthModelManager]) takes an
* ImageNet-normalized NCHW image and outputs depth; imported models take [0, 1] RGB and
* their output polarity is resolved later by the bokeh preprocessor. Models with a
* non-square input of the other orientation get the image rotated by 90 degrees.
* The model takes an ImageNet-normalized NCHW FLOAT32 image and outputs positive depth.
* It runs on the LiteRT GPU accelerator in FP16, in which it is exact; the CPU interpreter
* is the fallback. Input of the other orientation than the model's is rotated by 90 degrees.
*/
class DepthEstimator(context: Context) {
private var cpuInterpreter: Interpreter? = null
private var gpuModel: LiteRtGpuModel? = null
private var modelBuffer: MappedByteBuffer? = null
private lateinit var contract: DepthModelContract
private var isOfficialModel = false
private var isInitialized = false
internal val isReady: Boolean
get() = isInitialized
init {
val modelFile = DepthModelManager.requireInstalledModelFile(context)
try {
val fingerprint = StartupTrace.measure("DepthEstimator.fingerprint") {
DepthModelManager.installedModelFingerprint(context)
val modelFile = StartupTrace.measure("DepthEstimator.verifyModel") {
DepthModelManager.requireVerifiedModelFile(context)
}
isOfficialModel = fingerprint == DepthModelManager.OFFICIAL_MODEL_SHA256
val buffer = StartupTrace.measure("DepthEstimator.mapModelFile") {
FileInputStream(modelFile).channel.use { channel ->
channel.map(FileChannel.MapMode.READ_ONLY, 0L, channel.size())
}
}
modelBuffer = buffer
val outputCount = Interpreter(buffer, Interpreter.Options().setUseXNNPACK(false)).use {
Interpreter(buffer, Interpreter.Options().setUseXNNPACK(false)).use {
contract = inspectDepthModelContract(it)
it.outputTensorCount
check(
contract.inputDataType == DataType.FLOAT32 &&
contract.outputDataType == DataType.FLOAT32 &&
it.outputTensorCount == 1
) { "Depth model does not match the Depth Anything 3 contract" }
}
gpuModel = createGpuModel(context, modelFile, fingerprint, outputCount)
gpuModel = createGpuModel(context, modelFile)
if (gpuModel == null) {
cpuInterpreter = createCpuInterpreter(buffer)
}
isInitialized = true
PLog.d(
TAG,
"Depth model ready: backend=${if (gpuModel != null) "GPU" else "CPU"} official=$isOfficialModel " +
"Depth model ready: backend=${if (gpuModel != null) "GPU" else "CPU"} " +
"input=${contract.inputWidth}x${contract.inputHeight} output=${contract.outputWidth}x${contract.outputHeight} " +
"inputLayout=${if (contract.inputChannelsFirst) "NCHW" else "NHWC"} " +
"inputType=${contract.inputDataType} outputType=${contract.outputDataType} outputIndex=${contract.outputTensorIndex}"
"inputLayout=${if (contract.inputChannelsFirst) "NCHW" else "NHWC"}"
)
} catch (e: Exception) {
close()
@@ -72,24 +71,8 @@ class DepthEstimator(context: Context) {
}
}
/**
* GPU needs one FLOAT32 input and one FLOAT32 output. The default model is converted
* for the LiteRT GPU delegate and is exact in FP16; imported models run in FP32.
*/
private fun createGpuModel(context: Context, file: File, fingerprint: String, outputCount: Int): LiteRtGpuModel? {
if (
contract.inputDataType != DataType.FLOAT32 ||
contract.outputDataType != DataType.FLOAT32 ||
outputCount != 1
) {
PLog.d(TAG, "Depth model contract is not GPU-eligible; using CPU")
return null
}
val precision = if (isOfficialModel) {
CompiledModel.GpuOptions.Precision.FP16
} else {
CompiledModel.GpuOptions.Precision.FP32
}
private fun createGpuModel(context: Context, file: File): LiteRtGpuModel? {
val precision = CompiledModel.GpuOptions.Precision.FP16
return try {
val cache = MlDelegateCacheFactory.create(
context = context,
@@ -97,7 +80,7 @@ class DepthEstimator(context: Context) {
cacheName = "depth_${precision.name.lowercase()}",
modelAssetName = file.name,
modelSizeBytes = file.length().toInt(),
modelFingerprint = fingerprint,
modelFingerprint = DepthModelManager.OFFICIAL_MODEL_SHA256,
)
StartupTrace.measure("DepthEstimator.CompiledModel(GPU)") {
LiteRtGpuModel.fromFile(
@@ -136,8 +119,7 @@ class DepthEstimator(context: Context) {
return try {
val pixels = readModelInputPixels(inputBitmap, rotate)
val raw = runGpu(pixels) ?: runCpu(pixels)
val disparity = if (isOfficialModel) depthToDisparity(raw) else raw
val map = normalize(disparity, contract.outputWidth, contract.outputHeight)
val map = normalize(depthToDisparity(raw), contract.outputWidth, contract.outputHeight)
if (rotate) rotateBack(map) else map
} catch (e: Exception) {
PLog.e(TAG, "Error during depth model inference", e)
@@ -174,35 +156,21 @@ class DepthEstimator(context: Context) {
private fun runCpu(pixels: IntArray): FloatArray {
val interpreter = cpuInterpreter ?: error("CPU depth interpreter is not available")
val outputTensor = interpreter.getOutputTensor(contract.outputTensorIndex)
val outputBuffer = TensorBuffer.createFixedSize(outputTensor.shape(), contract.outputDataType)
val inputBuffer = cpuInput(pixels, interpreter)
val outputBuffer = TensorBuffer.createFixedSize(
interpreter.getOutputTensor(contract.outputTensorIndex).shape(),
DataType.FLOAT32,
)
val input = floatInput(pixels)
val inputBuffer = LargeDirectBuffer.allocate(input.size.toLong() * Float.SIZE_BYTES, "Depth model input")
?: throw OutOfMemoryError("Failed to allocate depth model input buffer")
try {
if (interpreter.outputTensorCount == 1 && contract.outputTensorIndex == 0) {
interpreter.run(inputBuffer, outputBuffer.buffer)
} else {
interpreter.runForMultipleInputsOutputs(
arrayOf(inputBuffer),
mapOf(contract.outputTensorIndex to outputBuffer.buffer),
)
}
inputBuffer.asFloatBuffer().put(input)
inputBuffer.rewind()
interpreter.run(inputBuffer, outputBuffer.buffer)
} finally {
LargeDirectBuffer.free(inputBuffer)
}
return when (contract.outputDataType) {
DataType.FLOAT32 -> outputBuffer.floatArray
DataType.UINT8, DataType.INT8 -> {
val byteBuffer = outputBuffer.buffer
byteBuffer.rewind()
val bytes = ByteArray(outputBuffer.flatSize)
byteBuffer.get(bytes)
FloatArray(bytes.size) { i ->
if (contract.outputDataType == DataType.UINT8) (bytes[i].toInt() and 0xFF).toFloat()
else bytes[i].toFloat()
}
}
else -> error("Unsupported depth model output type: ${contract.outputDataType}")
}
return outputBuffer.floatArray
}
/**
@@ -239,14 +207,14 @@ class DepthEstimator(context: Context) {
return pixels
}
/** Normalized RGB channel value; ImageNet mean/std for the default model, [0, 1] otherwise. */
/** ImageNet-normalized RGB channel value. */
private fun channelValue(pixel: Int, channel: Int): Float {
val value = when (channel) {
0 -> (pixel shr 16) and 0xFF
1 -> (pixel shr 8) and 0xFF
else -> pixel and 0xFF
} / 255.0f
return if (isOfficialModel) (value - IMAGENET_MEAN[channel]) / IMAGENET_STD[channel] else value
return (value - IMAGENET_MEAN[channel]) / IMAGENET_STD[channel]
}
private fun floatInput(pixels: IntArray): FloatArray {
@@ -264,44 +232,7 @@ class DepthEstimator(context: Context) {
return out
}
private fun cpuInput(pixels: IntArray, interpreter: Interpreter): ByteBuffer {
val bytesPerChannel = when (contract.inputDataType) {
DataType.FLOAT32 -> Float.SIZE_BYTES
DataType.UINT8, DataType.INT8 -> Byte.SIZE_BYTES
else -> throw IllegalArgumentException("Unsupported depth model input type: ${contract.inputDataType}")
}
val buffer = LargeDirectBuffer.allocate(
pixels.size.toLong() * RGB_CHANNELS * bytesPerChannel,
"Depth model input"
) ?: throw OutOfMemoryError("Failed to allocate depth model input buffer")
if (contract.inputDataType == DataType.FLOAT32) {
buffer.asFloatBuffer().put(floatInput(pixels))
buffer.rewind()
return buffer
}
val quantization = interpreter.getInputTensor(0).quantizationParams()
fun putChannel(pixel: Int, channel: Int) {
val quantized = quantize(channelValue(pixel, channel), quantization.scale, quantization.zeroPoint)
buffer.put(
if (contract.inputDataType == DataType.UINT8) quantized.coerceIn(0, 255).toByte()
else quantized.coerceIn(-128, 127).toByte()
)
}
if (contract.inputChannelsFirst) {
for (channel in 0 until RGB_CHANNELS) for (pixel in pixels) putChannel(pixel, channel)
} else {
for (pixel in pixels) for (channel in 0 until RGB_CHANNELS) putChannel(pixel, channel)
}
buffer.rewind()
return buffer
}
private fun quantize(value: Float, scale: Float, zeroPoint: Int): Int {
require(scale > 0f) { "Quantized depth model input has no valid scale" }
return kotlin.math.round(value / scale + zeroPoint.toFloat()).toInt()
}
/** The default model outputs positive depth; disparity is its reciprocal. */
/** The model outputs positive depth; disparity is its reciprocal. */
private fun depthToDisparity(depth: FloatArray): FloatArray {
return FloatArray(depth.size) { i ->
val d = depth[i]
@@ -1,47 +0,0 @@
package com.hinnka.mycamera.ml
import java.io.File
import java.io.FileInputStream
import java.nio.charset.StandardCharsets
internal enum class DepthModelImportFormat {
TFLITE,
ZIP
}
/**
* Detects the selected model container by signature rather than its display name or MIME type.
* Document providers frequently expose .tflite files as application/octet-stream.
*/
internal fun detectDepthModelImportFormat(file: File): DepthModelImportFormat? {
if (!file.isFile) {
return null
}
val header = ByteArray(IMPORT_HEADER_SIZE)
val bytesRead = FileInputStream(file).use { input -> input.read(header) }
if (
bytesRead >= IMPORT_HEADER_SIZE &&
header.copyOfRange(4, 8).contentEquals(TFLITE_FILE_IDENTIFIER)
) {
return DepthModelImportFormat.TFLITE
}
if (
bytesRead >= ZIP_SIGNATURE_SIZE &&
header[0] == ZIP_SIGNATURE_PREFIX[0] &&
header[1] == ZIP_SIGNATURE_PREFIX[1] &&
(
header[2] == 0x03.toByte() && header[3] == 0x04.toByte() ||
header[2] == 0x05.toByte() && header[3] == 0x06.toByte() ||
header[2] == 0x07.toByte() && header[3] == 0x08.toByte()
)
) {
return DepthModelImportFormat.ZIP
}
return null
}
private const val IMPORT_HEADER_SIZE = 8
private const val ZIP_SIGNATURE_SIZE = 4
private val TFLITE_FILE_IDENTIFIER = "TFL3".toByteArray(StandardCharsets.US_ASCII)
private val ZIP_SIGNATURE_PREFIX = byteArrayOf(0x50, 0x4B)
@@ -1,7 +1,7 @@
package com.hinnka.mycamera.ml
import android.content.Context
import android.net.Uri
import com.hinnka.mycamera.gallery.GalleryManager
import com.hinnka.mycamera.utils.PLog
import java.io.File
import java.io.FileInputStream
@@ -13,7 +13,6 @@ import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.security.MessageDigest
import java.util.concurrent.TimeUnit
import java.util.zip.ZipInputStream
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
@@ -35,8 +34,6 @@ sealed interface DepthModelDownloadState {
val isInstalling: Boolean
) : DepthModelDownloadState
data object Importing : DepthModelDownloadState
data object Ready : DepthModelDownloadState
data object Failed : DepthModelDownloadState
@@ -45,34 +42,39 @@ sealed interface DepthModelDownloadState {
/**
* Owns the optional depth model lifecycle.
*
* The model is kept in app-private storage and is installed atomically only after
* it has been verified as a TFLite model compatible with the app's depth pipeline.
* The default model (Depth Anything 3 Small, LiteRT GPU FP16) is downloaded from a
* commit-pinned Hugging Face URL and additionally verified by exact size and SHA-256.
* The only accepted model is Depth Anything 3 Small (LiteRT GPU FP16), downloaded from a
* commit-pinned Hugging Face URL and verified by exact size, SHA-256 and tensor contract
* before it is installed atomically in app-private storage. Any other model file, the
* former Depth Anything V2 directory, their delegate caches and per-photo depth caches
* made by another model are removed.
*/
object DepthModelManager {
private const val TAG = "DepthModelManager"
private const val MODEL_DIRECTORY = "ml_models/depth"
private const val MODEL_FILE_NAME = "depth.tflite"
private const val MODEL_IMPORT_PART_FILE_NAME = "depth.import.part"
private const val MODEL_PART_FILE_NAME = "depth.tflite.part"
private const val EXPECTED_MODEL_SIZE_BYTES = 55_035_456L
private const val MAX_IMPORT_SIZE_BYTES = 256L * 1024L * 1024L
internal const val OFFICIAL_MODEL_SHA256 =
"e170369a72ba1bba7486a4d2de555639fccd0595a9bb5b5349f7733ed4aebd1f"
private const val MODEL_PATH =
"/litert-community/Depth-Anything-3-Small/resolve/" +
"5cd25d936e3fde2edef68f53b4123401454ac9c8/da3_small_gpu_fp16.tflite"
/**
* Before Depth Anything 3 the model lived here. The former default (Depth Anything V2,
* identified by its exact size) is removed; a user-imported model is carried over.
*/
/** Identifies per-photo depth caches made by the official model (see [RelativeDepthMapFile]). */
internal val OFFICIAL_MODEL_ID: Long = OFFICIAL_MODEL_SHA256.substring(0, 16).toULong(16).toLong()
/** Depth Anything V2 and imported models lived here before Depth Anything 3. */
private const val LEGACY_MODEL_DIRECTORY = "ml_models/depth_anything_v2"
private const val LEGACY_MODEL_FILE_NAME = "depth_anything_v2.tflite"
private const val LEGACY_DEFAULT_MODEL_SIZE_BYTES = 98_920_480L
/** no_backup delegate caches of former models: V2 (NNAPI) and imported FP32 models. */
private val LEGACY_DELEGATE_CACHE_DIRECTORIES = listOf(
"depth_estimator_delegate_cache",
"depth_fp32_delegate_cache",
)
/** Holds the model id whose per-photo depth caches were last swept. */
private const val DEPTH_CACHE_MARKER_FILE_NAME = "depth_cache_model"
private val lock = Any()
private val verificationLock = Any()
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
@@ -86,6 +88,9 @@ object DepthModelManager {
internal var installationRevision: Long = 0L
private set
/** Size and modification time of the installed file whose SHA-256 has been verified. */
private var verifiedModelStamp: Pair<Long, Long>? = null
val state: StateFlow<DepthModelDownloadState> = _state.asStateFlow()
fun observe(context: Context): StateFlow<DepthModelDownloadState> {
@@ -98,18 +103,36 @@ object DepthModelManager {
return installedModelFileOrNull(context.applicationContext) != null
}
/** The installed file when its size and header match the official model; cheap enough for UI. */
fun installedModelFileOrNull(context: Context): File? {
val modelFile = modelFile(context.applicationContext)
return modelFile.takeIf(::hasValidInstalledModelFile)
return modelFile.takeIf(::hasOfficialModelShape)
}
fun requireInstalledModelFile(context: Context): File {
return installedModelFileOrNull(context)
?: throw IllegalStateException("A compatible depth model is not installed")
}
internal fun installedModelFingerprint(context: Context): String {
return sha256(requireInstalledModelFile(context.applicationContext))
/**
* The installed model after its SHA-256 matched the official model, hashed once per
* installed file. A mismatching file is removed and the state returns to missing.
* Must not run on the main thread.
*/
internal fun requireVerifiedModelFile(context: Context): File {
val appContext = context.applicationContext
initialize(appContext)
// Hashing takes a separate lock so that UI calls of [isInstalled] never wait for it.
synchronized(verificationLock) {
val modelFile = installedModelFileOrNull(appContext)
?: throw IllegalStateException("The depth model is not installed")
val stamp = modelFile.length() to modelFile.lastModified()
if (verifiedModelStamp == stamp) return modelFile
if (sha256(modelFile) != OFFICIAL_MODEL_SHA256) {
PLog.w(TAG, "Installed depth model is not the official model; removing it")
modelFile.deleteIfExistsOrLog()
verifiedModelStamp = null
_state.value = DepthModelDownloadState.Missing
throw IllegalStateException("The installed depth model failed verification")
}
verifiedModelStamp = stamp
return modelFile
}
}
fun download(context: Context, source: HfModelSource) {
@@ -150,42 +173,12 @@ object DepthModelManager {
}
}
fun importModel(context: Context, source: Uri) {
val appContext = context.applicationContext
initialize(appContext)
synchronized(lock) {
if (operationJob?.isActive == true) {
return
}
_state.value = DepthModelDownloadState.Importing
val newJob = scope.launch(start = CoroutineStart.LAZY) {
try {
importAndInstall(appContext, source)
_state.value = DepthModelDownloadState.Ready
} catch (e: Exception) {
PLog.e(TAG, "Failed to import or install depth model", e)
_state.value = DepthModelDownloadState.Failed
}
}
operationJob = newJob
newJob.invokeOnCompletion {
synchronized(lock) {
if (operationJob === newJob) {
operationJob = null
}
}
}
newJob.start()
}
}
private fun initialize(context: Context) {
synchronized(lock) {
if (initialized) {
return
}
migrateLegacyModel(context)
removeLegacyModels(context)
_state.value = if (installedModelFileOrNull(context) != null) {
DepthModelDownloadState.Ready
} else {
@@ -193,30 +186,53 @@ object DepthModelManager {
}
initialized = true
}
scope.launch { purgeForeignDepthCaches(context) }
}
private fun migrateLegacyModel(context: Context) {
/**
* Only the downloaded Depth Anything 3 model is accepted: the former V2 / imported model
* directory, any installed file of another size, leftover temporary files and the delegate
* caches of former models are removed.
*/
private fun removeLegacyModels(context: Context) {
val legacyDirectory = File(context.filesDir, LEGACY_MODEL_DIRECTORY)
if (!legacyDirectory.exists()) return
val legacyModel = File(legacyDirectory, LEGACY_MODEL_FILE_NAME)
val target = modelFile(context)
if (
hasValidInstalledModelFile(legacyModel) &&
legacyModel.length() != LEGACY_DEFAULT_MODEL_SIZE_BYTES &&
!target.exists()
) {
try {
if (!modelDirectory(context).isDirectory && !modelDirectory(context).mkdirs()) {
throw IOException("Cannot create depth model directory")
}
installAtomically(legacyModel, target)
PLog.d(TAG, "Carried over imported depth model to ${target.absolutePath}")
} catch (e: IOException) {
PLog.e(TAG, "Cannot carry over imported depth model", e)
if (legacyDirectory.exists() && !legacyDirectory.deleteRecursively()) {
PLog.w(TAG, "Cannot remove legacy depth model directory: ${legacyDirectory.absolutePath}")
}
val installed = modelFile(context)
if (installed.exists() && !hasOfficialModelShape(installed)) {
PLog.d(TAG, "Removing a depth model that is not the official model")
installed.deleteIfExistsOrLog()
}
modelDirectory(context).listFiles()?.forEach { file ->
if (file.name != MODEL_FILE_NAME && file.name != MODEL_PART_FILE_NAME) {
if (!file.deleteRecursively()) PLog.w(TAG, "Cannot remove ${file.absolutePath}")
}
}
if (!legacyDirectory.deleteRecursively()) {
PLog.w(TAG, "Cannot remove legacy depth model directory: ${legacyDirectory.absolutePath}")
for (name in LEGACY_DELEGATE_CACHE_DIRECTORIES) {
val directory = File(context.noBackupFilesDir, name)
if (directory.exists() && !directory.deleteRecursively()) {
PLog.w(TAG, "Cannot remove legacy delegate cache: ${directory.absolutePath}")
}
}
}
/**
* Removes per-photo depth caches made by any other model once per official model id;
* caches read later are still checked against the model id on every read.
*/
private fun purgeForeignDepthCaches(context: Context) {
val marker = File(context.noBackupFilesDir, DEPTH_CACHE_MARKER_FILE_NAME)
val modelId = OFFICIAL_MODEL_ID.toString()
try {
if (marker.isFile && marker.readText() == modelId) return
val removed = GalleryManager.removeDepthCaches(context) { file ->
!RelativeDepthMapFile.isFromModel(file, OFFICIAL_MODEL_ID)
}
marker.writeText(modelId)
PLog.d(TAG, "Removed $removed depth caches of former depth models")
} catch (e: Exception) {
PLog.w(TAG, "Cannot remove depth caches of former depth models", e)
}
}
@@ -237,6 +253,9 @@ object DepthModelManager {
)
validateOfficialModel(modelPartFile)
installAtomically(modelPartFile, modelFile(context))
synchronized(verificationLock) {
verifiedModelStamp = modelFile(context).let { it.length() to it.lastModified() }
}
publishInstallation()
PLog.d(TAG, "Default depth model installed: ${modelFile(context).absolutePath}")
} finally {
@@ -244,65 +263,6 @@ object DepthModelManager {
}
}
private fun importAndInstall(context: Context, source: Uri) {
val modelDirectory = modelDirectory(context)
if (!modelDirectory.isDirectory && !modelDirectory.mkdirs()) {
throw IOException("Cannot create depth model directory: ${modelDirectory.absolutePath}")
}
val importPartFile = File(modelDirectory, MODEL_IMPORT_PART_FILE_NAME)
val modelPartFile = File(modelDirectory, MODEL_PART_FILE_NAME)
importPartFile.deleteIfExistsOrThrow()
modelPartFile.deleteIfExistsOrThrow()
try {
copyImportedSource(context, source, importPartFile)
when (detectDepthModelImportFormat(importPartFile)) {
DepthModelImportFormat.TFLITE -> {
Files.move(
importPartFile.toPath(),
modelPartFile.toPath(),
StandardCopyOption.REPLACE_EXISTING
)
}
DepthModelImportFormat.ZIP -> extractImportedModel(importPartFile, modelPartFile)
null -> throw IOException(
"Selected file is neither a TFLite model nor a ZIP archive"
)
}
validateImportedModel(modelPartFile)
installAtomically(modelPartFile, modelFile(context))
publishInstallation()
PLog.d(TAG, "Compatible depth model imported successfully")
} finally {
importPartFile.deleteIfExistsOrLog()
modelPartFile.deleteIfExistsOrLog()
}
}
private fun copyImportedSource(context: Context, source: Uri, target: File) {
val input = context.contentResolver.openInputStream(source)
?: throw IOException("Cannot open selected depth model file")
input.use {
FileOutputStream(target).use { output ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
var copiedBytes = 0L
while (true) {
val read = it.read(buffer)
if (read < 0) {
break
}
copiedBytes += read
if (copiedBytes > MAX_IMPORT_SIZE_BYTES) {
throw IOException("Selected depth model file exceeds import size limit")
}
output.write(buffer, 0, read)
}
output.fd.sync()
}
}
}
private fun downloadModel(url: String, target: File) {
val request = Request.Builder()
.url(url)
@@ -354,52 +314,6 @@ object DepthModelManager {
)
}
private fun extractImportedModel(archive: File, target: File) {
var tfliteEntryFound = false
var extractedBytes = 0L
var lastCompatibilityError: Exception? = null
FileInputStream(archive).use { fileInput ->
ZipInputStream(fileInput).use { zipInput ->
var entry = zipInput.nextEntry
while (entry != null) {
if (!entry.isDirectory) {
target.deleteIfExistsOrThrow()
FileOutputStream(target).use { output ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
val read = zipInput.read(buffer)
if (read < 0) break
extractedBytes += read
if (extractedBytes > MAX_IMPORT_SIZE_BYTES) {
throw IOException("Depth model ZIP exceeds import size limit")
}
output.write(buffer, 0, read)
}
output.fd.sync()
}
if (detectDepthModelImportFormat(target) == DepthModelImportFormat.TFLITE) {
tfliteEntryFound = true
try {
validateImportedModel(target)
zipInput.closeEntry()
return
} catch (e: Exception) {
lastCompatibilityError = e
}
}
}
zipInput.closeEntry()
entry = zipInput.nextEntry
}
}
}
target.deleteIfExistsOrLog()
if (!tfliteEntryFound) {
throw IOException("Depth model archive does not contain a TFLite model")
}
throw IOException("Depth model archive has no compatible TFLite model", lastCompatibilityError)
}
private fun validateOfficialModel(file: File) {
if (!hasTfliteHeader(file) || file.length() != EXPECTED_MODEL_SIZE_BYTES) {
throw IOException("Default depth model has an invalid size or TFLite header")
@@ -407,13 +321,6 @@ object DepthModelManager {
if (sha256(file) != OFFICIAL_MODEL_SHA256) {
throw IOException("Depth model checksum mismatch")
}
validateImportedModel(file)
}
private fun validateImportedModel(file: File) {
if (!hasValidInstalledModelFile(file)) {
throw IOException("Depth model has an invalid size or TFLite header")
}
try {
Interpreter(file).use(::inspectDepthModelContract)
} catch (e: Exception) {
@@ -444,11 +351,8 @@ object DepthModelManager {
}
}
private fun hasValidInstalledModelFile(file: File): Boolean {
if (!file.isFile || file.length() < TFLITE_HEADER_SIZE || file.length() > MAX_IMPORT_SIZE_BYTES) {
return false
}
return hasTfliteHeader(file)
private fun hasOfficialModelShape(file: File): Boolean {
return file.isFile && file.length() == EXPECTED_MODEL_SIZE_BYTES && hasTfliteHeader(file)
}
private fun hasTfliteHeader(file: File): Boolean {
@@ -1,12 +1,9 @@
package com.hinnka.mycamera.ml
import android.graphics.Bitmap
/**
* Normalized relative disparity produced by the monocular depth model.
*
* Values remain floating point until the bokeh renderer. Larger/smaller polarity
* is resolved separately because imported models do not share one convention.
* Values remain floating point until the bokeh renderer.
*/
data class RelativeDepthMap(
val width: Int,
@@ -19,17 +16,4 @@ data class RelativeDepthMap(
"Depth data size does not match dimensions"
}
}
companion object {
/** Reads the red channel of a legacy 8-bit depth bitmap. */
fun fromBitmap(bitmap: Bitmap): RelativeDepthMap {
val pixels = IntArray(bitmap.width * bitmap.height)
bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
val values = FloatArray(pixels.size)
for (index in pixels.indices) {
values[index] = ((pixels[index] shr 16) and 0xff) / 255.0f
}
return RelativeDepthMap(bitmap.width, bitmap.height, values)
}
}
}
@@ -8,24 +8,41 @@ import java.io.DataOutputStream
import java.io.File
import java.io.IOException
/** Versioned, lossless cache for normalized relative depth. */
/**
* Versioned, lossless cache for normalized relative depth. The header records the depth
* model that produced it; a cache of another model or format version is not read.
*/
object RelativeDepthMapFile {
private const val MAGIC = 0x50484450 // "PHDP"
private const val VERSION = 1
private const val VERSION = 2
private const val MAX_PIXEL_COUNT = 16_777_216L
/** Whether [file] is a cache of this format made by [modelId]; reads the header only. */
fun isFromModel(file: File, modelId: Long): Boolean {
return try {
DataInputStream(BufferedInputStream(AtomicFile(file).openRead(), HEADER_BYTES)).use { input ->
input.readInt() == MAGIC && input.readInt() == VERSION && input.readLong() == modelId
}
} catch (_: IOException) {
false
}
}
@Throws(IOException::class)
fun read(file: File): RelativeDepthMap {
fun read(file: File, modelId: Long): RelativeDepthMap {
val atomicFile = AtomicFile(file)
DataInputStream(BufferedInputStream(atomicFile.openRead())).use { input ->
val magic = input.readInt()
val version = input.readInt()
val width = input.readInt()
val height = input.readInt()
val pixelCount = width.toLong() * height.toLong()
if (magic != MAGIC || version != VERSION) {
throw IOException("Unsupported depth cache header")
}
if (input.readLong() != modelId) {
throw IOException("Depth cache was made by another depth model")
}
val width = input.readInt()
val height = input.readInt()
val pixelCount = width.toLong() * height.toLong()
if (width <= 0 || height <= 0 || pixelCount > MAX_PIXEL_COUNT) {
throw IOException("Invalid depth cache dimensions: ${width}x$height")
}
@@ -43,7 +60,7 @@ object RelativeDepthMapFile {
}
@Throws(IOException::class)
fun write(file: File, depthMap: RelativeDepthMap) {
fun write(file: File, depthMap: RelativeDepthMap, modelId: Long) {
file.parentFile?.mkdirs()
val atomicFile = AtomicFile(file)
val output = atomicFile.startWrite()
@@ -51,6 +68,7 @@ object RelativeDepthMapFile {
try {
data.writeInt(MAGIC)
data.writeInt(VERSION)
data.writeLong(modelId)
data.writeInt(depthMap.width)
data.writeInt(depthMap.height)
for (value in depthMap.values) {
@@ -64,4 +82,6 @@ object RelativeDepthMapFile {
throw error
}
}
private const val HEADER_BYTES = 16
}
@@ -409,23 +409,285 @@ internal object BokehShaders {
* neighbours of its layer lie within 0.01, otherwise 1e-5, times the range
* Gaussian exp(-dBin^2 / 2 sigma^2) of 256 bins around the centre. The
* weighted median bin is the first bin whose cumulative vote exceeds half
* the total, found by two radix-16 histogram passes over the window; its
* value is the weighted mean of the samples inside that bin, so float
* layers do not terrace to 8 bits.
* R is recomposed from the filtered layers; A is unchanged.
* the total; its value is the weighted mean of the samples inside that bin,
* so float layers do not terrace to 8 bits. R is recomposed from the
* filtered layers; A is unchanged.
*
* The window radius is compiled in, sizing the tile to the window. Each
* tile sample carries both layers' bins and flatness votes, so the three
* window passes per layer only read shared memory. The radix counters are
* per invocation, lane-minor in shared memory; shared memory stays within
* the GLES 3.1 minimum of 16 KiB at [LAYER_MEDIAN_MAX_RADIUS].
* The filter runs in three passes:
* 1. [LAYER_MEDIAN_META_COMPUTE_SHADER] stores each pixel's bins, flatness
* votes and fp16 layers once, plus the bin range of every 8-row column
* chunk.
* 2. [layerMedianSlidingComputeShader] gives each invocation one column
* segment of [LAYER_MEDIAN_SEGMENT_ROWS] rows. When every window of the
* segment spans fewer than [LAYER_MEDIAN_SLIDING_BINS] bins, a sliding
* integer histogram of that span (vote counts and fixed-point depth sums
* per bin) replaces the per-pixel window scans. The range weight only
* depends on the bin, so it is applied when the histogram is queried and
* cancels inside the median bin. Segments spanning more bins append
* their 8x8 tiles to an indirect dispatch.
* 3. [layerMedianTileComputeShader] filters those tiles with the per-pixel
* radix search over the shared-memory window.
*/
fun layerMedianComputeShader(radius: Int): String {
val LAYER_MEDIAN_META_COMPUTE_SHADER = """#version 310 es
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp uimage2D;
layout(local_size_x = 8, local_size_y = 8) in;
// x: G bin | B bin << 8, y: G flat | B flat << 1, z / w: G / B as fp16 bits.
layout(rgba16ui, binding = 0) writeonly uniform highp uimage2D uMetaImage;
// Per column and 8-row chunk: G min | G max << 8 | B min << 16 | B max << 24.
layout(r32ui, binding = 1) writeonly uniform highp uimage2D uChunkImage;
uniform sampler2D uDepthTexture;
uniform float uFlatThreshold;
uniform int uGroupRowOffset;
shared uint lowG[8];
shared uint highG[8];
shared uint lowB[8];
shared uint highB[8];
int depthBin(float value) {
return int(clamp(value, 0.0, 1.0) * 255.0);
}
void main() {
ivec2 size = textureSize(uDepthTexture, 0);
ivec2 local = ivec2(gl_LocalInvocationID.xy);
ivec2 group = ivec2(gl_WorkGroupID.xy) + ivec2(0, uGroupRowOffset);
ivec2 pixel = group * 8 + local;
if (local.y == 0) {
lowG[local.x] = 255u;
highG[local.x] = 0u;
lowB[local.x] = 255u;
highB[local.x] = 0u;
}
barrier();
if (pixel.x < size.x && pixel.y < size.y) {
vec2 layers = texelFetch(uDepthTexture, pixel, 0).gb;
bvec2 isFlat = bvec2(true);
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
vec2 neighbour = texelFetch(uDepthTexture, clamp(pixel + ivec2(x, y), ivec2(0), size - 1), 0).gb;
isFlat = bvec2(isFlat.x && abs(neighbour.x - layers.x) <= uFlatThreshold,
isFlat.y && abs(neighbour.y - layers.y) <= uFlatThreshold);
}
}
uint binG = uint(depthBin(layers.x));
uint binB = uint(depthBin(layers.y));
imageStore(uMetaImage, pixel, uvec4(
binG | (binB << 8),
(isFlat.x ? 1u : 0u) | (isFlat.y ? 2u : 0u),
packHalf2x16(vec2(layers.x, 0.0)),
packHalf2x16(vec2(layers.y, 0.0))));
atomicMin(lowG[local.x], binG);
atomicMax(highG[local.x], binG);
atomicMin(lowB[local.x], binB);
atomicMax(highB[local.x], binB);
}
barrier();
if (local.y == 0 && pixel.x < size.x && group.y * 8 < size.y) {
imageStore(uChunkImage, ivec2(pixel.x, group.y), uvec4(
lowG[local.x] | (highG[local.x] << 8) | (lowB[local.x] << 16) | (highB[local.x] << 24)));
}
}
""".trimIndent()
const val LAYER_MEDIAN_SEGMENT_ROWS = 32
const val LAYER_MEDIAN_SLIDING_BINS = 16
/** Rows of one sliding dispatch: an 8x8 group of column segments. */
const val LAYER_MEDIAN_BAND_ROWS = 8 * LAYER_MEDIAN_SEGMENT_ROWS
/**
* Sliding-histogram pass. Shared memory: three 16-bin integer histograms
* per invocation (12 KiB, lane-minor) and the range table, within the
* GLES 3.1 minimum of 16 KiB.
*/
fun layerMedianSlidingComputeShader(radius: Int): String {
require(radius in 1..LAYER_MEDIAN_MAX_RADIUS) { "Layer median radius $radius out of range" }
return """#version 310 es
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp uimage2D;
layout(local_size_x = 8, local_size_y = 8) in;
const int RADIUS = $radius;
const int SEGMENT = $LAYER_MEDIAN_SEGMENT_ROWS;
const int BINS = $LAYER_MEDIAN_SLIDING_BINS;
const int LANES = 64;
// Fixed-point depth: (2R+1)^2 samples of |depth| <= 4 stay inside int32.
const float DEPTH_SCALE = 1048576.0;
// Flat votes count in the low half, edge votes in the high half.
const int EDGE_COUNT = 65536;
layout(rgba16ui, binding = 1) readonly uniform highp uimage2D uMetaImage;
layout(r32ui, binding = 2) readonly uniform highp uimage2D uChunkImage;
layout(rgba16f, binding = 0) writeonly uniform highp image2D uLayerImage;
layout(std430, binding = 0) buffer TileList {
uint groupCountX;
uint groupCountY;
uint groupCountZ;
uint reserved;
uint tiles[];
};
uniform sampler2D uDepthTexture;
uniform float uRangeSigmaBins;
uniform float uEdgeWeight;
uniform int uGroupRowOffset;
shared int histCount[BINS * LANES];
shared int histFlatDepth[BINS * LANES];
shared int histEdgeDepth[BINS * LANES];
shared float rangeWeight[256];
shared uint segmentFailed[8];
ivec2 size;
int lane;
void addRow(int column, int row, int layer, int low, int direction) {
int y = clamp(row, 0, size.y - 1);
for (int dx = -RADIUS; dx <= RADIUS; dx++) {
uvec4 meta = imageLoad(uMetaImage, ivec2(clamp(column + dx, 0, size.x - 1), y));
int slot = (int((meta.x >> uint(8 * layer)) & 255u) - low) * LANES + lane;
float depth = unpackHalf2x16(layer == 0 ? meta.z : meta.w).x;
int quantized = direction * int(round(depth * DEPTH_SCALE));
if (((meta.y >> uint(layer)) & 1u) != 0u) {
histCount[slot] += direction;
histFlatDepth[slot] += quantized;
} else {
histCount[slot] += direction * EDGE_COUNT;
histEdgeDepth[slot] += quantized;
}
}
}
float vote(int slot) {
int count = histCount[slot];
return float(count & 65535) + uEdgeWeight * float(count >> 16);
}
float median(int low, int centerBin) {
float total = 0.0;
for (int i = 0; i < BINS; i++) {
total += vote(i * LANES + lane) * rangeWeight[abs(low + i - centerBin)];
}
float halfTotal = 0.5 * total;
float below = 0.0;
for (int i = 0; i < BINS; i++) {
int slot = i * LANES + lane;
float binVote = vote(slot);
below += binVote * rangeWeight[abs(low + i - centerBin)];
if (below > halfTotal) {
return (float(histFlatDepth[slot]) + uEdgeWeight * float(histEdgeDepth[slot])) /
(DEPTH_SCALE * binVote);
}
}
// No bin reaching half the vote leaves the last bin, as the radix search does.
int lastSlot = (255 - low) * LANES + lane;
if (255 - low < BINS && vote(lastSlot) > 0.0) {
return (float(histFlatDepth[lastSlot]) + uEdgeWeight * float(histEdgeDepth[lastSlot])) /
(DEPTH_SCALE * vote(lastSlot));
}
return 1.0;
}
void main() {
size = imageSize(uMetaImage);
lane = int(gl_LocalInvocationIndex);
for (int i = lane; i < 256; i += LANES) {
rangeWeight[i] = exp(-float(i * i) / (2.0 * uRangeSigmaBins * uRangeSigmaBins));
}
int segment = int(gl_LocalInvocationID.y);
if (gl_LocalInvocationID.x == 0u) segmentFailed[segment] = 0u;
barrier();
int column = int(gl_GlobalInvocationID.x);
int firstRow = ((int(gl_WorkGroupID.y) + uGroupRowOffset) * 8 + segment) * SEGMENT;
bool inBounds = column < size.x && firstRow < size.y;
int endRow = min(firstRow + SEGMENT, size.y);
ivec2 low = ivec2(0);
if (inBounds) {
int firstChunk = max(firstRow - RADIUS, 0) / 8;
int lastChunk = min(endRow - 1 + RADIUS, size.y - 1) / 8;
uvec2 minBin = uvec2(255u);
uvec2 maxBin = uvec2(0u);
for (int dx = -RADIUS; dx <= RADIUS; dx++) {
int x = clamp(column + dx, 0, size.x - 1);
for (int chunk = firstChunk; chunk <= lastChunk; chunk++) {
uint range = imageLoad(uChunkImage, ivec2(x, chunk)).r;
minBin = min(minBin, uvec2(range & 255u, (range >> 16) & 255u));
maxBin = max(maxBin, uvec2((range >> 8) & 255u, range >> 24));
}
}
if (maxBin.x - minBin.x >= uint(BINS) || maxBin.y - minBin.y >= uint(BINS)) {
atomicOr(segmentFailed[segment], 1u);
}
low = ivec2(minBin);
}
barrier();
if (segmentFailed[segment] != 0u) {
if (gl_LocalInvocationID.x == 0u) {
uint tileX = gl_WorkGroupID.x;
for (int tileY = firstRow / 8; tileY * 8 < endRow; tileY++) {
uint index = atomicAdd(groupCountX, 1u);
tiles[index] = tileX | (uint(tileY) << 16);
}
}
return;
}
if (!inBounds) return;
float subject[SEGMENT];
for (int layer = 0; layer < 2; layer++) {
int layerLow = low[layer];
for (int i = 0; i < BINS; i++) {
int slot = i * LANES + lane;
histCount[slot] = 0;
histFlatDepth[slot] = 0;
histEdgeDepth[slot] = 0;
}
for (int row = firstRow - RADIUS; row <= firstRow + RADIUS; row++) {
addRow(column, row, layer, layerLow, 1);
}
for (int row = firstRow; row < endRow; row++) {
uvec4 meta = imageLoad(uMetaImage, ivec2(column, row));
float filtered = median(layerLow, int((meta.x >> uint(8 * layer)) & 255u));
if (layer == 0) {
subject[row - firstRow] = filtered;
} else {
vec4 center = texelFetch(uDepthTexture, ivec2(column, row), 0);
float subjectDepth = subject[row - firstRow];
imageStore(uLayerImage, ivec2(column, row),
vec4(mix(filtered, subjectDepth, center.a), subjectDepth, filtered, center.a));
}
if (row + 1 < endRow) {
addRow(column, row - RADIUS, layer, layerLow, -1);
addRow(column, row + RADIUS + 1, layer, layerLow, 1);
}
}
}
}
""".trimIndent()
}
/**
* Per-pixel weighted median of the tiles listed by the sliding pass, one
* 8x8 work group per listed tile. The window radius is compiled in, sizing
* the shared tile to the window; the three window passes per layer only
* read shared memory. The radix counters are per invocation, lane-minor in
* shared memory; shared memory stays within the GLES 3.1 minimum of 16 KiB
* at [LAYER_MEDIAN_MAX_RADIUS].
*/
fun layerMedianTileComputeShader(radius: Int): String {
require(radius in 1..LAYER_MEDIAN_MAX_RADIUS) { "Layer median radius $radius out of range" }
return """#version 310 es
precision highp float;
precision highp int;
precision highp sampler2D;
precision highp uimage2D;
layout(local_size_x = 8, local_size_y = 8) in;
const int RADIUS = $radius;
@@ -439,10 +701,17 @@ internal object BokehShaders {
// Radix counters of each invocation at [digit * LANES + lane].
shared float radixWeight[RADIX * LANES];
layout(rgba16ui, binding = 1) readonly uniform highp uimage2D uMetaImage;
layout(rgba16f, binding = 0) writeonly uniform highp image2D uLayerImage;
layout(std430, binding = 0) readonly buffer TileList {
uint groupCountX;
uint groupCountY;
uint groupCountZ;
uint reserved;
uint tiles[];
};
uniform sampler2D uDepthTexture;
uniform float uRangeSigmaBins;
uniform float uFlatThreshold;
uniform float uEdgeWeight;
int depthBin(float value) {
@@ -521,30 +790,23 @@ internal object BokehShaders {
}
void main() {
ivec2 size = textureSize(uDepthTexture, 0);
ivec2 origin = ivec2(gl_WorkGroupID.xy) * 8 - RADIUS;
ivec2 size = imageSize(uMetaImage);
uint tile = tiles[gl_WorkGroupID.x];
ivec2 tileOrigin = ivec2(int(tile & 65535u), int(tile >> 16)) * 8;
ivec2 origin = tileOrigin - RADIUS;
int lane = int(gl_LocalInvocationIndex);
for (int i = lane; i < TILE * TILE; i += LANES) {
ivec2 pixel = clamp(origin + ivec2(i % TILE, i / TILE), ivec2(0), size - 1);
vec2 layers = texelFetch(uDepthTexture, pixel, 0).gb;
bvec2 isFlat = bvec2(true);
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
vec2 neighbour = texelFetch(uDepthTexture, clamp(pixel + ivec2(x, y), ivec2(0), size - 1), 0).gb;
isFlat = bvec2(isFlat.x && abs(neighbour.x - layers.x) <= uFlatThreshold,
isFlat.y && abs(neighbour.y - layers.y) <= uFlatThreshold);
}
}
tileDepth[i] = layers;
tileMeta[i] = uint(depthBin(layers.x)) | (uint(depthBin(layers.y)) << 8) |
(isFlat.x ? 65536u : 0u) | (isFlat.y ? 131072u : 0u);
uvec4 meta = imageLoad(uMetaImage, pixel);
tileDepth[i] = vec2(unpackHalf2x16(meta.z).x, unpackHalf2x16(meta.w).x);
tileMeta[i] = meta.x | (meta.y << 16);
}
for (int i = lane; i < 256; i += LANES) {
rangeWeight[i] = exp(-float(i * i) / (2.0 * uRangeSigmaBins * uRangeSigmaBins));
}
barrier();
ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);
ivec2 pixel = tileOrigin + ivec2(gl_LocalInvocationID.xy);
if (pixel.x >= size.x || pixel.y >= size.y) return;
ivec2 local = ivec2(gl_LocalInvocationID.xy) + RADIUS;
vec4 center = texelFetch(uDepthTexture, pixel, 0);
@@ -1137,12 +1399,22 @@ internal object BokehShaders {
* `Integrate`: row prefix sums of the gradient field; the weight channel
* is clamped at zero on every step. The deltas are cleared for the next
* scatter. uAccumulate adds into the target instead of overwriting it.
*
* One work group per row; each lane owns a contiguous run of columns. The
* clamped weight recurrence w <- max(w + d, 0) composes as w -> max(w + A, B),
* so the lanes' runs are combined by a shared-memory scan of (sum, A, B).
* Sums stay in the fixed-point integers of the deltas, so the result does
* not depend on the summation order.
*/
val INTEGRATE_COMPUTE_SHADER = """#version 310 es
precision highp float;
precision highp int;
layout(local_size_x = 128) in;
const int LANES = 128;
// Below any reachable weight; one delta lifts it to the clamp at zero.
const int NO_FLOOR = -1073741824;
layout(std430, binding = 0) buffer Deltas { int deltas[]; };
layout(std430, binding = 1) buffer Target { vec4 target[]; };
@@ -1150,20 +1422,66 @@ internal object BokehShaders {
uniform int uRows;
uniform int uAccumulate;
shared ivec3 colorScan[LANES];
shared ivec2 weightScan[LANES];
void main() {
int row = int(gl_GlobalInvocationID.x);
int row = int(gl_WorkGroupID.x);
int lane = int(gl_LocalInvocationIndex);
int run = (uWidth + LANES - 1) / LANES;
int first = min(lane * run, uWidth);
int last = min(first + run, uWidth);
// This lane's run as a color sum and a weight map w -> max(w + A, B).
ivec3 color = ivec3(0);
ivec2 weight = ivec2(0, NO_FLOOR);
if (row < uRows) {
for (int x = first; x < last; x++) {
int base = (row * uWidth + x) * 4;
color += ivec3(deltas[base], deltas[base + 1], deltas[base + 2]);
int d = deltas[base + 3];
weight = ivec2(weight.x + d, max(weight.y + d, 0));
}
}
colorScan[lane] = color;
weightScan[lane] = weight;
barrier();
// Inclusive Hillis-Steele scan; the earlier run is applied first.
for (int offset = 1; offset < LANES; offset <<= 1) {
ivec3 earlierColor = ivec3(0);
ivec2 earlierWeight = ivec2(0, NO_FLOOR);
bool combine = lane >= offset;
if (combine) {
earlierColor = colorScan[lane - offset];
earlierWeight = weightScan[lane - offset];
}
barrier();
if (combine) {
ivec2 own = weightScan[lane];
colorScan[lane] = earlierColor + colorScan[lane];
weightScan[lane] = ivec2(earlierWeight.x + own.x, max(earlierWeight.y + own.x, own.y));
}
barrier();
}
if (row >= uRows) return;
vec4 sum = vec4(0.0);
for (int x = 0; x < uWidth; x++) {
ivec3 colorSum = ivec3(0);
int weightSum = 0;
if (lane > 0) {
colorSum = colorScan[lane - 1];
ivec2 incoming = weightScan[lane - 1];
weightSum = max(incoming.x, incoming.y);
}
for (int x = first; x < last; x++) {
int index = row * uWidth + x;
int base = index * 4;
ivec4 delta = ivec4(deltas[base], deltas[base + 1], deltas[base + 2], deltas[base + 3]);
colorSum += ivec3(deltas[base], deltas[base + 1], deltas[base + 2]);
weightSum = max(weightSum + deltas[base + 3], 0);
deltas[base] = 0;
deltas[base + 1] = 0;
deltas[base + 2] = 0;
deltas[base + 3] = 0;
sum += vec4(delta) / $DELTA_FIXED_SCALE;
sum.w = max(sum.w, 0.0);
vec4 sum = vec4(vec3(colorSum), float(weightSum)) / $DELTA_FIXED_SCALE;
if (uAccumulate != 0) {
vec4 current = target[index];
target[index] = current + sum;
@@ -1174,7 +1492,7 @@ internal object BokehShaders {
}
""".trimIndent()
/** `ResampleToImageDomain` of the half-resolution domain + `AdditiveBlend` into the band. */
/** `ResampleToImageDomain` of a 2^-level domain (bilinear) + `AdditiveBlend` into the band. */
val UPSAMPLE_ADD_COMPUTE_SHADER = """#version 310 es
precision highp float;
precision highp int;
@@ -1189,6 +1507,7 @@ internal object BokehShaders {
uniform int uSourceWidth;
uniform int uSourceRow;
uniform int uSourceRows;
uniform float uScale;
vec4 fetchSource(int x, int y) {
int cx = clamp(x, 0, uSourceWidth - 1);
@@ -1201,7 +1520,7 @@ internal object BokehShaders {
int x = int(gl_GlobalInvocationID.x);
int row = int(gl_GlobalInvocationID.y);
if (x >= uWidth || row >= uStripRows) return;
vec2 position = (vec2(x, uStripRow + row) + 0.5) * 0.5 - 0.5;
vec2 position = (vec2(x, uStripRow + row) + 0.5) * uScale - 0.5;
ivec2 base = ivec2(floor(position));
vec2 f = position - vec2(base);
vec4 top = mix(fetchSource(base.x, base.y), fetchSource(base.x + 1, base.y), f.x);
@@ -2,8 +2,8 @@ package com.hinnka.mycamera.processor
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.hinnka.mycamera.gallery.GalleryManager
import com.hinnka.mycamera.ml.DepthModelManager
import com.hinnka.mycamera.ml.RelativeDepthMap
import com.hinnka.mycamera.ml.RelativeDepthMapFile
import com.hinnka.mycamera.ml.SharedDepthEstimator
@@ -49,32 +49,15 @@ class DepthBokehProcessor(context: Context) {
}
var depthMap: RelativeDepthMap? = null
var floatDepthFile: java.io.File? = null
if (photoId != null) {
floatDepthFile = GalleryManager.getFloatDepthFile(context, photoId)
if (floatDepthFile.exists()) {
depthMap = try {
RelativeDepthMapFile.read(floatDepthFile)
} catch (error: Exception) {
PLog.w(TAG, "Unable to read floating-point depth cache", error)
null
}
}
// Existing photos may only have the former 8-bit PNG cache. Read it
// once and migrate it without changing its already-quantized values.
if (depthMap == null) {
val legacyDepthFile = GalleryManager.getDepthFile(context, photoId)
if (legacyDepthFile.exists()) {
val legacyBitmap = BitmapFactory.decodeFile(legacyDepthFile.absolutePath)
if (legacyBitmap != null) {
try {
depthMap = RelativeDepthMap.fromBitmap(legacyBitmap)
} finally {
legacyBitmap.recycle()
}
}
}
val floatDepthFile = photoId?.let { GalleryManager.getFloatDepthFile(context, it) }
if (floatDepthFile != null && floatDepthFile.exists()) {
depthMap = try {
RelativeDepthMapFile.read(floatDepthFile, DepthModelManager.OFFICIAL_MODEL_ID)
} catch (error: Exception) {
// Another depth model's or format's cache: replace it with this model's depth.
PLog.w(TAG, "Discarding depth cache: ${error.message}")
floatDepthFile.delete()
null
}
}
@@ -83,18 +66,11 @@ class DepthBokehProcessor(context: Context) {
if (depthMap != null && floatDepthFile != null) {
try {
RelativeDepthMapFile.write(floatDepthFile, depthMap)
RelativeDepthMapFile.write(floatDepthFile, depthMap, DepthModelManager.OFFICIAL_MODEL_ID)
} catch (error: Exception) {
PLog.w(TAG, "Unable to write floating-point depth cache", error)
}
}
} else if (floatDepthFile != null && !floatDepthFile.exists()) {
// Persist a successfully migrated legacy cache as the new versioned format.
try {
RelativeDepthMapFile.write(floatDepthFile, depthMap)
} catch (error: Exception) {
PLog.w(TAG, "Unable to migrate floating-point depth cache", error)
}
}
var result: Bitmap? = null
@@ -6,6 +6,7 @@ import kotlin.math.ceil
import kotlin.math.exp
import kotlin.math.max
import kotlin.math.roundToInt
import java.util.concurrent.CompletableFuture
/**
* CPU-side masks of the layered depth (docs/lrmobile-lens-blur-evidence.md §9).
@@ -47,20 +48,23 @@ internal object DepthLayerMasks {
val scaleY = lensTexel / texelY
val edges = CropEdges(region.left > 0f, region.right < 1f, region.top > 0f, region.bottom < 1f)
val subject = FloatArray(width * height) { if (mask.values[it] > SUBJECT_THRESHOLD) 1f else 0f }
val background = FloatArray(width * height) { 1f - subject[it] }
val subjectInterior = morph(subject, width, height, scaleX, scaleY, SUBJECT_ERODE, false, edges, 0f)
// The two layers are independent; the background chain runs on a pool worker.
val backgroundInterior = CompletableFuture.supplyAsync {
val background = ByteArray(width * height) { if (mask.values[it] > SUBJECT_THRESHOLD) 0 else 1 }
morph(background, width, height, scaleX, scaleY, BACKGROUND_ERODE, false, edges, 1)
.let { morph(it, width, height, scaleX, scaleY, BACKGROUND_DILATE, true, edges, 1) }
.let { morph(it, width, height, scaleX, scaleY, BACKGROUND_ERODE, false, edges, 1) }
.let { blur(it, width, height, scaleX, scaleY, edges, 1f) }
}
val subject = ByteArray(width * height) { if (mask.values[it] > SUBJECT_THRESHOLD) 1 else 0 }
val subjectValues = morph(subject, width, height, scaleX, scaleY, SUBJECT_ERODE, false, edges, 0)
.let { blur(it, width, height, scaleX, scaleY, edges, 0f) }
val backgroundInterior = morph(background, width, height, scaleX, scaleY, BACKGROUND_ERODE, false, edges, 1f)
.let { morph(it, width, height, scaleX, scaleY, BACKGROUND_DILATE, true, edges, 1f) }
.let { morph(it, width, height, scaleX, scaleY, BACKGROUND_ERODE, false, edges, 1f) }
.let { blur(it, width, height, scaleX, scaleY, edges, 1f) }
val backgroundValues = backgroundInterior.join()
return FloatArray(width * height * 2).also { out ->
for (index in 0 until width * height) {
out[2 * index] = subjectInterior[index]
out[2 * index + 1] = backgroundInterior[index]
out[2 * index] = subjectValues[index]
out[2 * index + 1] = backgroundValues[index]
}
}
}
@@ -151,9 +155,14 @@ internal object DepthLayerMasks {
private class CropEdges(val left: Boolean, val right: Boolean, val top: Boolean, val bottom: Boolean)
/** Square erosion / dilation by [iterations] Lens Blur texels (3x3 iterated), separable. */
/**
* Square erosion / dilation by [iterations] Lens Blur texels (3x3 iterated), separable,
* of a binary (0 / 1) mask. Each pass slides a count of set samples over the window:
* erosion keeps a sample whose whole window is set, dilation one whose window holds any,
* so the cost per sample does not depend on the radius.
*/
private fun morph(
source: FloatArray,
source: ByteArray,
width: Int,
height: Int,
scaleX: Float,
@@ -161,40 +170,57 @@ internal object DepthLayerMasks {
iterations: Int,
dilate: Boolean,
edges: CropEdges,
outside: Float,
): FloatArray {
outside: Byte,
): ByteArray {
val radiusX = (iterations * scaleX).roundToInt()
val radiusY = (iterations * scaleY).roundToInt()
val horizontal = FloatArray(width * height)
val row = FloatArray(width + 2 * radiusX)
val windowX = 2 * radiusX + 1
val windowY = 2 * radiusY + 1
val horizontal = ByteArray(width * height)
for (y in 0 until height) {
padRow(source, width, y, radiusX, edges, outside, row)
val rowBase = y * width
fun sample(x: Int): Int {
if ((x < 0 && edges.left) || (x >= width && edges.right)) return outside.toInt()
return source[rowBase + x.coerceIn(0, width - 1)].toInt()
}
var count = 0
for (x in -radiusX..radiusX) count += sample(x)
for (x in 0 until width) {
var value = row[x + radiusX]
for (i in x..x + 2 * radiusX) {
value = if (dilate) max(value, row[i]) else minOf(value, row[i])
}
horizontal[y * width + x] = value
horizontal[rowBase + x] = morphValue(count, windowX, dilate)
count += sample(x + radiusX + 1) - sample(x - radiusX)
}
}
val result = FloatArray(width * height)
val column = FloatArray(height + 2 * radiusY)
for (x in 0 until width) {
padColumn(horizontal, width, height, x, radiusY, edges, outside, column)
for (y in 0 until height) {
var value = column[y + radiusY]
for (i in y..y + 2 * radiusY) {
value = if (dilate) max(value, column[i]) else minOf(value, column[i])
}
result[y * width + x] = value
// Vertical counts per column, slid row by row so every access stays row-major.
val outsideCount = outside.toInt()
val counts = IntArray(width)
fun accumulate(row: Int, sign: Int) {
if ((row < 0 && edges.top) || (row >= height && edges.bottom)) {
if (outsideCount != 0) for (x in 0 until width) counts[x] += sign * outsideCount
return
}
val base = row.coerceIn(0, height - 1) * width
for (x in 0 until width) counts[x] += sign * horizontal[base + x]
}
for (row in -radiusY..radiusY) accumulate(row, 1)
val result = ByteArray(width * height)
for (y in 0 until height) {
val rowBase = y * width
for (x in 0 until width) result[rowBase + x] = morphValue(counts[x], windowY, dilate)
if (y + 1 < height) {
accumulate(y + radiusY + 1, 1)
accumulate(y - radiusY, -1)
}
}
return result
}
/** `cv::GaussianBlur(11x11, sigma 4)` of the Lens Blur grid, separable. */
private fun morphValue(setCount: Int, window: Int, dilate: Boolean): Byte =
if (dilate) { if (setCount > 0) 1 else 0 } else { if (setCount == window) 1 else 0 }
/** Separable Gaussian of a binary mask; the vertical pass walks rows to stay row-major. */
private fun blur(
source: FloatArray,
source: ByteArray,
width: Int,
height: Int,
scaleX: Float,
@@ -216,7 +242,14 @@ internal object DepthLayerMasks {
val horizontal = FloatArray(width * height)
val row = FloatArray(width + 2 * halfX)
for (y in 0 until height) {
padRow(source, width, y, halfX, edges, outside, row)
for (i in row.indices) {
val x = i - halfX
row[i] = if ((x < 0 && edges.left) || (x >= width && edges.right)) {
outside
} else {
source[y * width + x.coerceIn(0, width - 1)].toFloat()
}
}
for (x in 0 until width) {
var sum = 0f
for (i in kernelX.indices) sum += kernelX[i] * row[x + i]
@@ -224,62 +257,23 @@ internal object DepthLayerMasks {
}
}
val result = FloatArray(width * height)
val column = FloatArray(height + 2 * halfY)
for (x in 0 until width) {
padColumn(horizontal, width, height, x, halfY, edges, outside, column)
for (y in 0 until height) {
var sum = 0f
for (i in kernelY.indices) sum += kernelY[i] * column[y + i]
result[y * width + x] = sum.coerceIn(0f, 1f)
val sum = FloatArray(width)
for (y in 0 until height) {
sum.fill(0f)
for (i in kernelY.indices) {
val sourceRow = y + i - halfY
val weight = kernelY[i]
if ((sourceRow < 0 && edges.top) || (sourceRow >= height && edges.bottom)) {
val value = weight * outside
for (x in 0 until width) sum[x] += value
} else {
val base = sourceRow.coerceIn(0, height - 1) * width
for (x in 0 until width) sum[x] += weight * horizontal[base + x]
}
}
val rowBase = y * width
for (x in 0 until width) result[rowBase + x] = sum[x].coerceIn(0f, 1f)
}
return result
}
/** Row [y] with [radius] edge-handled samples on each side: `padded[radius + x]` is pixel x. */
private fun padRow(
values: FloatArray,
width: Int,
y: Int,
radius: Int,
edges: CropEdges,
outside: Float,
padded: FloatArray,
) {
for (i in 0 until width + 2 * radius) padded[i] = sampleRow(values, width, y, i - radius, edges, outside)
}
/** Column [x] with [radius] edge-handled samples on each side: `padded[radius + y]` is pixel y. */
private fun padColumn(
values: FloatArray,
width: Int,
height: Int,
x: Int,
radius: Int,
edges: CropEdges,
outside: Float,
padded: FloatArray,
) {
for (i in 0 until height + 2 * radius) {
padded[i] = sampleColumn(values, width, height, x, i - radius, edges, outside)
}
}
private fun sampleRow(values: FloatArray, width: Int, y: Int, x: Int, edges: CropEdges, outside: Float): Float {
if ((x < 0 && edges.left) || (x >= width && edges.right)) return outside
return values[y * width + x.coerceIn(0, width - 1)]
}
private fun sampleColumn(
values: FloatArray,
width: Int,
height: Int,
x: Int,
y: Int,
edges: CropEdges,
outside: Float,
): Float {
if ((y < 0 && edges.top) || (y >= height && edges.bottom)) return outside
return values[y.coerceIn(0, height - 1) * width + x]
}
}
@@ -431,22 +431,26 @@ internal class LensBlurLayout(
).toFloat()
maxRadius = maxRadiusFull * radiusScale
// Splat domains in working pixels: level l scatters radii up to
// SPLAT_DOMAIN_RADIUS * 2^l at 2^-l resolution, so the radius in domain
// pixels, and with it the scatter cost per source, stays bounded
// independently of the photo's resolution. The last level is open.
data class Descriptor(val level: Int, val minRadius: Float, val maxRadius: Float)
val descriptors = if (originalLongEdge >= 2017) {
val t = ((4032f - originalLongEdge) / 2016f).coerceIn(0f, 1f)
val split = t * (maxRadiusFull - 8f) + 8f
listOf(Descriptor(0, 0f, split), Descriptor(1, split - 2f, -1f))
} else {
listOf(Descriptor(0, 0f, -1f))
val descriptors = List(SPLAT_LEVELS) { level ->
Descriptor(
level = level,
minRadius = if (level == 0) 0f else SPLAT_DOMAIN_RADIUS * (1 shl (level - 1)) - SPLAT_DOMAIN_OVERLAP,
maxRadius = if (level == SPLAT_LEVELS - 1) -1f else SPLAT_DOMAIN_RADIUS * (1 shl level),
)
}
val effective = min(params.blurAmount * maxRadiusFull + 1f, maxRadiusFull)
val effective = min(params.blurAmount * maxRadiusFull + 1f, maxRadiusFull) * radiusScale
val active = descriptors.filter { effective >= it.minRadius }.map { descriptor ->
val clamped = if (descriptor.maxRadius == -1f || effective < descriptor.maxRadius) {
effective
} else {
descriptor.maxRadius
}
Descriptor(descriptor.level, descriptor.minRadius * radiusScale, clamped * radiusScale)
Descriptor(descriptor.level, descriptor.minRadius, clamped)
}
var spread = active.first().maxRadius
for (descriptor in active.drop(1)) {
@@ -472,6 +476,14 @@ internal class LensBlurLayout(
)
}
private companion object {
/** Largest scatter radius of a bounded splat domain, in that domain's pixels. */
const val SPLAT_DOMAIN_RADIUS = 16f
/** Working-pixel radius range over which adjacent domains cross-fade. */
const val SPLAT_DOMAIN_OVERLAP = 2f
const val SPLAT_LEVELS = 3
}
/** `Process_32` band selection: bands whose radius range holds at least one source. */
fun activeBands(histogram: IntArray): List<Int> {
val cumulative = IntArray(histogram.size)
@@ -77,6 +77,10 @@ class OglBokehProcessor {
/** Pixels per bulk copy of the RGBA8 depth classification readback. */
private const val CLASSIFICATION_CHUNK_PIXELS = 16384
/** Indirect dispatch arguments (x, y, z) and padding ahead of the median tile list. */
private const val TILE_LIST_HEADER_WORDS = 4
private const val GPU_SLICES_IN_FLIGHT = 2
}
private data class DomainTargets(
@@ -103,7 +107,9 @@ class OglBokehProcessor {
private var guidedSolveProgramId = 0
private var guidedMeanProgramId = 0
private var guidedApplyProgramId = 0
private var layerMedianProgramId = 0
private var layerMedianMetaProgramId = 0
private var layerMedianSlidingProgramId = 0
private var layerMedianTileProgramId = 0
private var jbuUpsampleProgramId = 0
private var depthRefineProgramId = 0
private var cocProgramId = 0
@@ -132,6 +138,7 @@ class OglBokehProcessor {
private var eglContext = EGL14.EGL_NO_CONTEXT
private var eglSurface = EGL14.EGL_NO_SURFACE
private var gpuWindow: GlesGpuScheduler.PassWindow? = null
private val textures = mutableSetOf<Int>()
private val buffers = mutableSetOf<Int>()
private var maxStorageBlockSize = 0L
@@ -187,6 +194,7 @@ class OglBokehProcessor {
)
initEGL(originalImage.width, originalImage.height)
gpuWindow = GlesGpuScheduler.PassWindow(TAG, GPU_SLICES_IN_FLIGHT)
initGL(bokehStyle, medianRadius)
GLES30.glDisable(GLES30.GL_DITHER)
GLES30.glDisable(GLES30.GL_BLEND)
@@ -285,14 +293,15 @@ class OglBokehProcessor {
uniform1i(compositeProgramId, "uLinearInput", if (linearInput) 1 else 0)
uniform1i(compositeProgramId, "uHighlights", if (highlightTex != null) 1 else 0)
bindSampler(compositeProgramId, "uHighlightTexture", 4, highlightTex ?: inputTex)
// Row bands, each submitted on its own, keep the UI renderer's GPU slots open.
// Row bands, paced one at a time, keep the UI renderer's GPU slots open.
GLES30.glEnable(GLES30.GL_SCISSOR_TEST)
var bandRow = 0
while (bandRow < originalImage.height) {
val rows = min(OUTPUT_BAND_ROWS, originalImage.height - bandRow)
GLES30.glScissor(0, bandRow, originalImage.width, rows)
drawQuad(compositeProgramId)
GlesGpuScheduler.yieldToUiRenderer()
paced("lens blur composite") {
GLES30.glScissor(0, bandRow, originalImage.width, rows)
drawQuad(compositeProgramId)
}
bandRow += rows
}
GLES30.glDisable(GLES30.GL_SCISSOR_TEST)
@@ -473,23 +482,76 @@ class OglBokehProcessor {
release(upsampledTex)
val layersTex = track(createStorageTexture(width, height))
useProgram(layerMedianProgramId)
val metaTex = track(createUintStorageTexture(width, height, GLES30.GL_RGBA16UI))
val chunkRows = ceilDiv(height, GlesComputeWorkGroup.IMAGE_TILE_SIZE)
val chunkTex = track(createUintStorageTexture(width, chunkRows, GLES30.GL_R32UI))
val groupsX = GlesComputeWorkGroup.imageGroupCount(width)
// Alternating lists: resetting one band's header never waits for the previous band's dispatch.
val tileLists = IntArray(2) {
createBuffer(
(TILE_LIST_HEADER_WORDS + groupsX.toLong() * BokehShaders.LAYER_MEDIAN_BAND_ROWS / 8) * 4,
"layer median tile list",
)
}
val bandGroupRows = BokehShaders.LAYER_MEDIAN_BAND_ROWS / GlesComputeWorkGroup.IMAGE_TILE_SIZE
val bandCount = ceilDiv(height, BokehShaders.LAYER_MEDIAN_BAND_ROWS)
useProgram(layerMedianMetaProgramId)
GLES31.glBindImageTexture(0, metaTex, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16UI)
GLES31.glBindImageTexture(1, chunkTex, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI)
bindSampler(layerMedianMetaProgramId, "uDepthTexture", 0, refinedTex)
uniform1f(layerMedianMetaProgramId, "uFlatThreshold", LAYER_MEDIAN_FLAT_THRESHOLD)
for (band in 0 until bandCount) {
paced("layer median meta") {
uniform1i(layerMedianMetaProgramId, "uGroupRowOffset", band * bandGroupRows)
GLES31.glDispatchCompute(groupsX, min(bandGroupRows, chunkRows - band * bandGroupRows), 1)
}
}
GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT)
GLES31.glBindImageTexture(1, 0, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI)
val header = ByteBuffer.allocateDirect(TILE_LIST_HEADER_WORDS * 4).order(ByteOrder.nativeOrder())
header.asIntBuffer().put(intArrayOf(0, 1, 1, 0))
GLES31.glBindImageTexture(0, layersTex, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F)
bindSampler(layerMedianProgramId, "uDepthTexture", 0, refinedTex)
uniform1f(layerMedianProgramId, "uRangeSigmaBins", LAYER_MEDIAN_SIGMA_BINS)
uniform1f(layerMedianProgramId, "uFlatThreshold", LAYER_MEDIAN_FLAT_THRESHOLD)
uniform1f(layerMedianProgramId, "uEdgeWeight", LAYER_MEDIAN_EDGE_WEIGHT)
GLES31.glDispatchCompute(
GlesComputeWorkGroup.imageGroupCount(width),
GlesComputeWorkGroup.imageGroupCount(height),
1,
)
GLES31.glBindImageTexture(1, metaTex, 0, false, 0, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16UI)
GLES31.glBindImageTexture(2, chunkTex, 0, false, 0, GLES31.GL_READ_ONLY, GLES30.GL_R32UI)
for (band in 0 until bandCount) {
val tileList = tileLists[band % 2]
paced("layer median") {
header.position(0)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, tileList)
GLES31.glBufferSubData(GLES31.GL_SHADER_STORAGE_BUFFER, 0, TILE_LIST_HEADER_WORDS * 4, header)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, tileList)
GLES31.glBindBuffer(GLES31.GL_DISPATCH_INDIRECT_BUFFER, tileList)
useProgram(layerMedianSlidingProgramId)
bindSampler(layerMedianSlidingProgramId, "uDepthTexture", 0, refinedTex)
uniform1f(layerMedianSlidingProgramId, "uRangeSigmaBins", LAYER_MEDIAN_SIGMA_BINS)
uniform1f(layerMedianSlidingProgramId, "uEdgeWeight", LAYER_MEDIAN_EDGE_WEIGHT)
uniform1i(layerMedianSlidingProgramId, "uGroupRowOffset", band)
GLES31.glDispatchCompute(groupsX, 1, 1)
GLES31.glMemoryBarrier(GLES31.GL_COMMAND_BARRIER_BIT or GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
useProgram(layerMedianTileProgramId)
bindSampler(layerMedianTileProgramId, "uDepthTexture", 0, refinedTex)
uniform1f(layerMedianTileProgramId, "uRangeSigmaBins", LAYER_MEDIAN_SIGMA_BINS)
uniform1f(layerMedianTileProgramId, "uEdgeWeight", LAYER_MEDIAN_EDGE_WEIGHT)
GLES31.glDispatchComputeIndirect(0)
}
}
GLES31.glMemoryBarrier(
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or GLES31.GL_FRAMEBUFFER_BARRIER_BIT or
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT,
)
GLES31.glBindBuffer(GLES31.GL_DISPATCH_INDIRECT_BUFFER, 0)
GLES31.glBindImageTexture(0, 0, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F)
GLES31.glBindImageTexture(1, 0, 0, false, 0, GLES31.GL_READ_ONLY, GLES30.GL_RGBA16UI)
GLES31.glBindImageTexture(2, 0, 0, false, 0, GLES31.GL_READ_ONLY, GLES30.GL_R32UI)
requireNoGlError("layer discontinuity median")
tileLists.forEach(::releaseBuffer)
release(metaTex)
release(chunkTex)
release(refinedTex)
return layersTex
}
@@ -916,12 +978,19 @@ class OglBokehProcessor {
) {
val stripPixels = width.toLong() * STRIP_ROWS
val deltaBuffers = targets.map { target ->
val rows = if (target.domain.level == 0) STRIP_ROWS else STRIP_ROWS / 2 + 3
val words = target.width.toLong() * rows * 4
val words = target.width.toLong() * domainStripRows(target.domain.level) * 4
createBuffer(words * 4, "lens blur gradient field").also { clearBuffer(it, words.toInt()) }
}
val halfIntegratedBuffer = targets.firstOrNull { it.domain.level != 0 }?.let { target ->
createBuffer(target.width.toLong() * (STRIP_ROWS / 2 + 3) * 16, "lens blur half-domain field")
// Integrated field of each downsampled domain, resampled into the working-resolution band.
val integratedBuffers = targets.map { target ->
if (target.domain.level == 0) {
0
} else {
createBuffer(
target.width.toLong() * domainStripRows(target.domain.level) * 16,
"lens blur domain field",
)
}
}
val bandBuffer = createBuffer(stripPixels * 16, "lens blur band").also {
clearBuffer(it, (stripPixels * 4).toInt())
@@ -945,7 +1014,7 @@ class OglBokehProcessor {
while (stripRow < height) {
val stripRows = min(STRIP_ROWS, height - stripRow)
for ((nearField, bands) in listOf(NEAR_PASS to nearBands, FAR_PASS to farBands)) {
for (bandIndex in bands) {
for (bandIndex in bands) paced("lens blur band") {
val band = layout.bands[bandIndex]
targets.forEachIndexed { domainIndex, target ->
val domain = target.domain
@@ -953,8 +1022,13 @@ class OglBokehProcessor {
val (rowLow, rowHigh) = if (domain.level == 0) {
stripRow to stripRow + stripRows
} else {
val low = max(0, floor(stripRow / 2.0 - 0.25).toInt())
val high = min(target.height, floor((stripRow + stripRows - 1) / 2.0 - 0.25).toInt() + 2)
// Domain rows of the bilinear upsample taps at (y + 0.5) / 2^level - 0.5.
val factor = (1 shl domain.level).toDouble()
val low = max(0, floor((stripRow + 0.5) / factor - 0.5).toInt())
val high = min(
target.height,
floor((stripRow + stripRows - 0.5) / factor - 0.5).toInt() + 2,
)
low to high
}
scatter(
@@ -965,7 +1039,7 @@ class OglBokehProcessor {
if (domain.level == 0) {
integrate(deltaBuffers[domainIndex], bandBuffer, target.width, rowHigh - rowLow, true)
} else {
val integrated = checkNotNull(halfIntegratedBuffer)
val integrated = integratedBuffers[domainIndex]
integrate(deltaBuffers[domainIndex], integrated, target.width, rowHigh - rowLow, false)
upsampleAdd(integrated, bandBuffer, width, stripRow, stripRows, target, rowLow, rowHigh)
}
@@ -978,11 +1052,11 @@ class OglBokehProcessor {
if (nearField) LensBlurParams.NEAR_ALPHA_GAIN else LensBlurParams.FAR_ALPHA_GAIN,
linearInput,
)
// Submit each band on its own so the UI renderer is not queued behind a strip.
GlesGpuScheduler.yieldToUiRenderer()
}
}
store(nearBuffer, farBuffer, nearTex, farTex, width, stripRow, stripRows)
paced("lens blur store") {
store(nearBuffer, farBuffer, nearTex, farTex, width, stripRow, stripRows)
}
stripRow += stripRows
}
GLES31.glMemoryBarrier(
@@ -990,7 +1064,7 @@ class OglBokehProcessor {
)
requireNoGlError("lens blur strips")
deltaBuffers.forEach(::releaseBuffer)
halfIntegratedBuffer?.let(::releaseBuffer)
integratedBuffers.filter { it != 0 }.forEach(::releaseBuffer)
releaseBuffer(bandBuffer)
releaseBuffer(nearBuffer)
releaseBuffer(farBuffer)
@@ -1065,6 +1139,10 @@ class OglBokehProcessor {
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
}
/** Delta / integrated rows of one strip in a 2^-level domain, including the upsample's apron. */
private fun domainStripRows(level: Int): Int =
if (level == 0) STRIP_ROWS else STRIP_ROWS / (1 shl level) + 3
private fun integrate(deltaBuffer: Int, targetBuffer: Int, width: Int, rows: Int, accumulate: Boolean) {
useProgram(integrateProgramId)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, deltaBuffer)
@@ -1072,7 +1150,7 @@ class OglBokehProcessor {
uniform1i(integrateProgramId, "uWidth", width)
uniform1i(integrateProgramId, "uRows", rows)
uniform1i(integrateProgramId, "uAccumulate", if (accumulate) 1 else 0)
GLES31.glDispatchCompute(GlesComputeWorkGroup.linearGroupCount(rows), 1, 1)
GLES31.glDispatchCompute(rows, 1, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
}
@@ -1095,6 +1173,7 @@ class OglBokehProcessor {
uniform1i(upsampleAddProgramId, "uSourceWidth", target.width)
uniform1i(upsampleAddProgramId, "uSourceRow", sourceRow)
uniform1i(upsampleAddProgramId, "uSourceRows", sourceRowEnd - sourceRow)
uniform1f(upsampleAddProgramId, "uScale", target.domain.scale)
GLES31.glDispatchCompute(
GlesComputeWorkGroup.imageGroupCount(width),
GlesComputeWorkGroup.imageGroupCount(stripRows),
@@ -1350,6 +1429,33 @@ class OglBokehProcessor {
return texture
}
/** Immutable unsigned-integer image (RGBA16UI / R32UI) written and read through image units only. */
private fun createUintStorageTexture(width: Int, height: Int, internalFormat: Int): Int {
val texture = IntArray(1)
GLES30.glGenTextures(1, texture, 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture[0])
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, internalFormat, width, height)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST)
requireNoGlError("lens blur integer image ${width}x$height")
return texture[0]
}
/**
* Submits one bounded slice of GPU work. At most two slices are in flight, so the
* UI renderer is never queued behind more than one slice of this pipeline.
*/
private inline fun paced(label: String, block: () -> Unit) {
val window = checkNotNull(gpuWindow) { "GPU pass window is not initialised" }
window.beginPass(label)
try {
block()
} finally {
window.endPass()
}
}
/** Immutable RGBA16F target of write-only image stores, sampled with linear filtering afterwards. */
private fun createStorageTexture(width: Int, height: Int): Int {
val texture = IntArray(1)
@@ -1556,8 +1662,14 @@ class OglBokehProcessor {
guidedSolveProgramId = createComputeProgram(BokehShaders.GUIDED_SOLVE_COMPUTE_SHADER, "guided depth solve")
guidedMeanProgramId = createComputeProgram(BokehShaders.GUIDED_MEAN_COMPUTE_SHADER, "guided depth mean")
guidedApplyProgramId = createComputeProgram(BokehShaders.GUIDED_APPLY_COMPUTE_SHADER, "guided depth apply")
layerMedianProgramId = createComputeProgram(
BokehShaders.layerMedianComputeShader(medianRadius), "layer depth median",
layerMedianMetaProgramId = createComputeProgram(
BokehShaders.LAYER_MEDIAN_META_COMPUTE_SHADER, "layer depth median meta",
)
layerMedianSlidingProgramId = createComputeProgram(
BokehShaders.layerMedianSlidingComputeShader(medianRadius), "layer depth median sliding",
)
layerMedianTileProgramId = createComputeProgram(
BokehShaders.layerMedianTileComputeShader(medianRadius), "layer depth median tiles",
)
maxProgramId = createComputeProgram(BokehShaders.MAX_COMPUTE_SHADER, "lens blur maximum")
histogramProgramId = createComputeProgram(BokehShaders.HISTOGRAM_COMPUTE_SHADER, "lens blur histogram")
@@ -1646,11 +1758,12 @@ class OglBokehProcessor {
private fun releaseGL() {
if (eglDisplay != EGL14.EGL_NO_DISPLAY && eglContext != EGL14.EGL_NO_CONTEXT) {
gpuWindow?.drain("lens blur release")
textures.forEach { GLES30.glDeleteTextures(1, intArrayOf(it), 0) }
buffers.forEach { GLES31.glDeleteBuffers(1, intArrayOf(it), 0) }
listOf(
guidedMomentsProgramId, guidedSolveProgramId, guidedMeanProgramId, guidedApplyProgramId,
layerMedianProgramId, jbuUpsampleProgramId, depthRefineProgramId, cocProgramId, cocSpreadProgramId,
layerMedianMetaProgramId, layerMedianSlidingProgramId, layerMedianTileProgramId, jbuUpsampleProgramId, depthRefineProgramId, cocProgramId, cocSpreadProgramId,
guideLuminanceProgramId, guideGradientProgramId, guideCombineProgramId, compositeProgramId,
maxProgramId, histogramProgramId, scatterProgramId, integrateProgramId, upsampleAddProgramId,
alphaBlendProgramId, storeProgramId, clearProgramId, depthReadbackProgramId, layerColorProgramId,
@@ -1660,6 +1773,7 @@ class OglBokehProcessor {
.filter { it != 0 }
.forEach { GLES30.glDeleteBuffers(1, intArrayOf(it), 0) }
}
gpuWindow = null
textures.clear()
buffers.clear()
@@ -1676,7 +1790,9 @@ class OglBokehProcessor {
guidedSolveProgramId = 0
guidedMeanProgramId = 0
guidedApplyProgramId = 0
layerMedianProgramId = 0
layerMedianMetaProgramId = 0
layerMedianSlidingProgramId = 0
layerMedianTileProgramId = 0
jbuUpsampleProgramId = 0
depthRefineProgramId = 0
cocProgramId = 0
@@ -1,7 +1,6 @@
package com.hinnka.mycamera.ui.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
@@ -25,11 +24,9 @@ fun DepthModelDownloadDialog(
source: HfModelSource,
onSourceChange: (HfModelSource) -> Unit,
onDownload: () -> Unit,
onImport: () -> Unit,
onDismiss: () -> Unit
) {
val isBusy = state is DepthModelDownloadState.Downloading ||
state is DepthModelDownloadState.Importing
val isBusy = state is DepthModelDownloadState.Downloading
AlertDialog(
onDismissRequest = onDismiss,
title = {
@@ -67,9 +64,7 @@ fun DepthModelDownloadDialog(
}
Spacer(modifier = Modifier.height(8.dp))
Text(
text = if (state is DepthModelDownloadState.Importing) {
stringResource(R.string.depth_model_importing)
} else if (
text = if (
state is DepthModelDownloadState.Downloading &&
state.isInstalling
) {
@@ -90,37 +85,21 @@ fun DepthModelDownloadDialog(
confirmButton = {
when (state) {
DepthModelDownloadState.Missing -> {
Row {
TextButton(onClick = onImport) {
Text(stringResource(R.string.depth_model_import_action))
}
TextButton(onClick = onDownload) {
Text(stringResource(R.string.depth_model_download_action))
}
TextButton(onClick = onDownload) {
Text(stringResource(R.string.depth_model_download_action))
}
}
DepthModelDownloadState.Failed -> {
Row {
TextButton(onClick = onImport) {
Text(stringResource(R.string.depth_model_import_action))
}
TextButton(onClick = onDownload) {
Text(stringResource(R.string.depth_model_retry))
}
TextButton(onClick = onDownload) {
Text(stringResource(R.string.depth_model_retry))
}
}
DepthModelDownloadState.Ready -> {
Row {
TextButton(onClick = onImport) {
Text(stringResource(R.string.depth_model_import_action))
}
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.depth_model_done))
}
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.depth_model_done))
}
}
is DepthModelDownloadState.Downloading -> Unit
DepthModelDownloadState.Importing -> Unit
}
},
dismissButton = {
@@ -213,11 +213,6 @@ fun GalleryEditScreen(
val isDepthModelInstalled = DepthModelManager.isInstalled(context)
var showDepthModelDownloadDialog by remember { mutableStateOf(false) }
var pendingVirtualAperture by remember { mutableStateOf<Float?>(null) }
val depthModelImportLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument()
) { uri ->
uri?.let { DepthModelManager.importModel(context, it) }
}
val colorFmModelState by remember(context.applicationContext) {
ColorFmModelManager.observe(context)
}.collectAsState()
@@ -2260,7 +2255,6 @@ fun GalleryEditScreen(
onSourceChange = { depthModelSource = it },
state = depthModelState,
onDownload = { DepthModelManager.download(context, depthModelSource) },
onImport = { depthModelImportLauncher.launch(arrayOf("*/*")) },
onDismiss = {
showDepthModelDownloadDialog = false
pendingVirtualAperture = null
@@ -574,11 +574,6 @@ fun SettingsScreen(
val isDepthModelInstalled = DepthModelManager.isInstalled(context)
var showDepthModelDownloadDialog by remember { mutableStateOf(false) }
var pendingDefaultVirtualAperture by remember { mutableStateOf<Float?>(null) }
val depthModelImportLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument()
) { uri ->
uri?.let { DepthModelManager.importModel(context, it) }
}
LaunchedEffect(depthModelState, pendingDefaultVirtualAperture) {
val pendingAperture = pendingDefaultVirtualAperture
@@ -878,7 +873,6 @@ fun SettingsScreen(
onSourceChange = { depthModelSource = it },
state = depthModelState,
onDownload = { DepthModelManager.download(context, depthModelSource) },
onImport = { depthModelImportLauncher.launch(arrayOf("*/*")) },
onDismiss = {
showDepthModelDownloadDialog = false
pendingDefaultVirtualAperture = null
@@ -809,14 +809,6 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
fun hasDepthInfo(photo: MediaData?): Boolean {
if (photo == null) return false
if (selectedTab == GalleryTab.SYSTEM) return false
val context = getApplication<Application>()
return GalleryManager.getFloatDepthFile(context, photo.id).exists() ||
GalleryManager.getDepthFile(context, photo.id).exists()
}
// 最新照片(用于相机界面显示入口)
private val _latestPhoto = MutableStateFlow<MediaData?>(null)
val latestPhoto: StateFlow<MediaData?> = _latestPhoto.asStateFlow()
@@ -1049,7 +1049,7 @@
<string name="virtual_aperture_viewfinder_hint">f/%1$s</string>
<string name="settings_default_virtual_aperture">預設虛擬光圈</string>
<string name="settings_default_virtual_aperture_description">開啟后,拍攝及匯入相片將自動應用所選光圈值的虛化效果。</string>
<string name="virtual_aperture_depth_model_description">使用目前已安裝的相容深度模型。首次使用時可下載預設模型,或匯入其他相容的 TFLite 模型。</string>
<string name="virtual_aperture_depth_model_description">使用 Depth Anything 3 深度模型,首次使用時需下載。</string>
<string name="gallery_large_aperture_blur_title">大光圈虛化</string>
<string name="gallery_large_aperture_blur_description">模擬大光圈的淺景深背景虛化效果</string>
<string name="gallery_bokeh_style_title">光斑風格</string>
@@ -1062,15 +1062,13 @@
<string name="edit_panel_expand">展開編輯面板</string>
<string name="edit_panel_minimize">最小化編輯面板</string>
<string name="depth_model_download_title">深度模型</string>
<string name="depth_model_download_description">景深虛化功能需要相容的 TFLite 深度模型:包含一個 RGB 影像輸入和一個單通道深度輸出。你可以下載預設的 Depth Anything 3 模型(約 55 MB),也可以匯入其他 TFLite 模型或包含模型的 ZIP 壓縮檔。模型將儲存在 App 的私人目錄中。</string>
<string name="depth_model_download_description">景深虛化功能需要 Depth Anything 3 深度模型(約 55 MB)。模型下載並驗證後將儲存在 App 的私人目錄中。</string>
<string name="depth_model_download_action">下載</string>
<string name="depth_model_import_action">匯入</string>
<string name="depth_model_downloading">正在下載模型…</string>
<string name="depth_model_downloading_progress">正在下載模型… %1$d%%</string>
<string name="depth_model_importing">正在匯入並驗證模型…</string>
<string name="depth_model_installing">正在驗證並安裝模型…</string>
<string name="depth_model_download_failed">模型匯入、下載或驗證失敗,請確認所選檔案或網路連線後重試。</string>
<string name="depth_model_download_ready">相容的深度模型已就緒,可匯入其他模型進行替換。</string>
<string name="depth_model_download_failed">模型下載或驗證失敗,請檢查網路連線後重試。</string>
<string name="depth_model_download_ready">深度模型已就緒。</string>
<string name="depth_model_retry">重試</string>
<string name="depth_model_done">完成</string>
<string name="recipe_tab_palette">調色盤</string>
+4 -6
View File
@@ -1257,7 +1257,7 @@
<string name="virtual_aperture_viewfinder_hint">f/%1$s</string>
<string name="settings_default_virtual_aperture">Ouverture virtuelle par défaut</string>
<string name="settings_default_virtual_aperture_description">Active automatiquement l\'ouverture virtuelle avec la valeur d\'ouverture choisie pour les nouvelles photos.</string>
<string name="virtual_aperture_depth_model_description">Utilise le modèle de profondeur compatible installé. Téléchargez le modèle par défaut ou importez un autre modèle TFLite compatible lors de la première utilisation.</string>
<string name="virtual_aperture_depth_model_description">Utilise le modèle de profondeur Depth Anything 3. Téléchargez-le lors de la première utilisation.</string>
<string name="gallery_large_aperture_blur_title">Flou à grande ouverture</string>
<string name="gallery_large_aperture_blur_description">Simule la faible profondeur de champ et le flou d\'arrière-plan d\'une grande ouverture</string>
<string name="gallery_bokeh_style_title">Style de bokeh</string>
@@ -1268,15 +1268,13 @@
<string name="edit_panel_expand">Développer les commandes de retouche</string>
<string name="edit_panel_minimize">Réduire les commandes de retouche</string>
<string name="depth_model_download_title">Modèle de profondeur</string>
<string name="depth_model_download_description">Le flou tenant compte de la profondeur nécessite un modèle de profondeur TFLite compatible, avec une entrée image RGB et une sortie de profondeur à un seul canal. Téléchargez le modèle Depth Anything 3 par défaut (environ 55 Mo), ou importez un autre modèle TFLite ou un ZIP en contenant un. Le modèle sera stocké en privé par l\'application.</string>
<string name="depth_model_download_description">Le flou tenant compte de la profondeur nécessite le modèle de profondeur Depth Anything 3 (environ 55 Mo). Il sera téléchargé, vérifié et stocké en privé par l\'application.</string>
<string name="depth_model_download_action">Télécharger</string>
<string name="depth_model_import_action">Importer</string>
<string name="depth_model_downloading">Téléchargement du modèle…</string>
<string name="depth_model_downloading_progress">Téléchargement du modèle… %1$d %%</string>
<string name="depth_model_importing">Importation et vérification du modèle…</string>
<string name="depth_model_installing">Vérification et installation du modèle…</string>
<string name="depth_model_download_failed">Le modèle n\'a pas pu être importé, téléchargé ou vérifié. Vérifiez le fichier sélectionné ou votre connexion, puis réessayez.</string>
<string name="depth_model_download_ready">Un modèle de profondeur compatible est prêt. Vous pouvez en importer un autre pour le remplacer.</string>
<string name="depth_model_download_failed">Le modèle n\'a pas pu être téléchargé ou vérifié. Vérifiez votre connexion, puis réessayez.</string>
<string name="depth_model_download_ready">Le modèle de profondeur est prêt.</string>
<string name="depth_model_retry">Réessayer</string>
<string name="depth_model_done">Terminé</string>
<string name="ai_denoise_title">Réduction du bruit profonde par IA</string>
+4 -6
View File
@@ -916,7 +916,7 @@
<string name="virtual_aperture">仮想絞り</string>
<string name="settings_default_virtual_aperture">デフォルト仮想絞り</string>
<string name="settings_default_virtual_aperture_description">新しい写真で、選択したF値の仮想絞りを自動有効化</string>
<string name="virtual_aperture_depth_model_description">インストール済みの対応深度モデルを使用します。初回使用時に既定モデルをダウンロードするか、別の対応TFLiteモデルを読み込んでください。</string>
<string name="virtual_aperture_depth_model_description">Depth Anything 3 深度モデルを使用します。初回使用時にダウンロードしてください。</string>
<string name="gallery_large_aperture_blur_title">大口径ボケ</string>
<string name="gallery_large_aperture_blur_description">大口径レンズの浅い被写界深度と背景ボケを再現します</string>
<string name="gallery_bokeh_style_title">ボケ味</string>
@@ -929,15 +929,13 @@
<string name="edit_panel_expand">編集コントロールを展開</string>
<string name="edit_panel_minimize">編集コントロールを折りたたむ</string>
<string name="depth_model_download_title">深度モデル</string>
<string name="depth_model_download_description">深度連動ボケには、RGB画像1入力・1ch深度出力の対応TFLite深度モデルが必要です。既定のDepth Anything 3モデル(約55MB)をダウンロードするか、別のTFLiteモデルまたはそれを含むZIPを読み込めます。モデルはアプリ内の非公開領域に保存されます。</string>
<string name="depth_model_download_description">深度連動ボケには Depth Anything 3 深度モデル(約55MB)が必要です。モデルはダウンロード・検証後、アプリ内の非公開領域に保存されます。</string>
<string name="depth_model_download_action">ダウンロード</string>
<string name="depth_model_import_action">読み込み</string>
<string name="depth_model_downloading">モデルをダウンロード中…</string>
<string name="depth_model_downloading_progress">モデルをダウンロード中… %1$d%%</string>
<string name="depth_model_importing">モデルを読み込み・検証中…</string>
<string name="depth_model_installing">モデルを検証・インストール中…</string>
<string name="depth_model_download_failed">モデルを読み込み、ダウンロード、または検証できませんでした。選択したファイルまたは接続を確認して、もう一度お試しください。</string>
<string name="depth_model_download_ready">対応深度モデルを利用できます。別のモデルを読み込んで置き換えることもできます。</string>
<string name="depth_model_download_failed">モデルをダウンロードまたは検証できませんでした。接続を確認して、もう一度お試しください。</string>
<string name="depth_model_download_ready">深度モデルを利用できます。</string>
<string name="depth_model_retry">再試行</string>
<string name="depth_model_done">完了</string>
<string name="ai_denoise_title">AIディープノイズ除去</string>
+4 -6
View File
@@ -1070,7 +1070,7 @@
<string name="virtual_aperture_viewfinder_hint">f/%1$s</string>
<string name="settings_default_virtual_aperture">默认虚拟光圈</string>
<string name="settings_default_virtual_aperture_description">开启后,拍摄及导入照片将自动应用所选光圈值的虚化效果。</string>
<string name="virtual_aperture_depth_model_description">使用当前已安装的兼容深度模型。首次使用时可下载默认模型,或导入其他兼容的 TFLite 模型。</string>
<string name="virtual_aperture_depth_model_description">使用 Depth Anything 3 深度模型,首次使用时需下载。</string>
<string name="gallery_large_aperture_blur_title">大光圈虚化</string>
<string name="gallery_large_aperture_blur_description">模拟大光圈的浅景深背景虚化效果</string>
<string name="gallery_bokeh_style_title">光斑风格</string>
@@ -1083,15 +1083,13 @@
<string name="edit_panel_expand">展开编辑面板</string>
<string name="edit_panel_minimize">最小化编辑面板</string>
<string name="depth_model_download_title">深度模型</string>
<string name="depth_model_download_description">景深虚化功能需要兼容的 TFLite 深度模型:包含一个 RGB 图像输入和一个单通道深度输出。你可以下载默认的 Depth Anything 3 模型(约 55 MB),也可以导入其他 TFLite 模型或包含模型的 ZIP 压缩包。模型将保存在应用的私有目录中。</string>
<string name="depth_model_download_description">景深虚化功能需要 Depth Anything 3 深度模型(约 55 MB)。模型下载并校验后将保存在应用的私有目录中。</string>
<string name="depth_model_download_action">下载</string>
<string name="depth_model_import_action">导入</string>
<string name="depth_model_downloading">正在下载模型…</string>
<string name="depth_model_downloading_progress">正在下载模型… %1$d%%</string>
<string name="depth_model_importing">正在导入并校验模型…</string>
<string name="depth_model_installing">正在校验并安装模型…</string>
<string name="depth_model_download_failed">模型导入、下载或校验失败,请确认所选文件或网络连接后重试。</string>
<string name="depth_model_download_ready">兼容的深度模型已就绪,可导入其他模型进行替换。</string>
<string name="depth_model_download_failed">模型下载或校验失败,请检查网络连接后重试。</string>
<string name="depth_model_download_ready">深度模型已就绪。</string>
<string name="depth_model_retry">重试</string>
<string name="depth_model_done">完成</string>
<string name="recipe_tab_palette">调色盘</string>
+4 -6
View File
@@ -1049,22 +1049,20 @@
<string name="virtual_aperture_viewfinder_hint">f/%1$s</string>
<string name="settings_default_virtual_aperture">預設虛擬光圈</string>
<string name="settings_default_virtual_aperture_description">開啟后,拍攝及匯入相片將自動應用所選光圈值的虛化效果。</string>
<string name="virtual_aperture_depth_model_description">使用目前已安裝的兼容深度模型。首次使用時可下載預設模型,或匯入其他兼容的 TFLite 模型。</string>
<string name="virtual_aperture_depth_model_description">使用 Depth Anything 3 深度模型,首次使用時需下載。</string>
<string name="gallery_large_aperture_blur_title">大光圈虛化</string>
<string name="gallery_large_aperture_blur_description">模擬大光圈的淺景深背景虛化效果</string>
<string name="edit_panel_title">編輯面板</string>
<string name="edit_panel_expand">展開編輯面板</string>
<string name="edit_panel_minimize">最小化編輯面板</string>
<string name="depth_model_download_title">深度模型</string>
<string name="depth_model_download_description">景深虛化功能需要兼容的 TFLite 深度模型:包含一個 RGB 圖像輸入和一個單通道深度輸出。你可以下載預設的 Depth Anything 3 模型(約 55 MB),也可以匯入其他 TFLite 模型或包含模型的 ZIP 壓縮檔。模型將儲存在 App 的私人目錄中。</string>
<string name="depth_model_download_description">景深虛化功能需要 Depth Anything 3 深度模型(約 55 MB)。模型下載並驗證後將儲存在 App 的私人目錄中。</string>
<string name="depth_model_download_action">下載</string>
<string name="depth_model_import_action">匯入</string>
<string name="depth_model_downloading">正在下載模型…</string>
<string name="depth_model_downloading_progress">正在下載模型… %1$d%%</string>
<string name="depth_model_importing">正在匯入並驗證模型…</string>
<string name="depth_model_installing">正在驗證並安裝模型…</string>
<string name="depth_model_download_failed">模型匯入、下載或驗證失敗,請確認所選檔案或網絡連線後重試。</string>
<string name="depth_model_download_ready">兼容的深度模型已就緒,可匯入其他模型進行替換。</string>
<string name="depth_model_download_failed">模型下載或驗證失敗,請檢查網絡連線後重試。</string>
<string name="depth_model_download_ready">深度模型已就緒。</string>
<string name="depth_model_retry">重試</string>
<string name="depth_model_done">完成</string>
<string name="recipe_tab_palette">調色盤</string>
+4 -6
View File
@@ -1049,7 +1049,7 @@
<string name="virtual_aperture_viewfinder_hint">f/%1$s</string>
<string name="settings_default_virtual_aperture">預設虛擬光圈</string>
<string name="settings_default_virtual_aperture_description">開啟后,拍攝及匯入相片將自動應用所選光圈值的虛化效果。</string>
<string name="virtual_aperture_depth_model_description">使用目前已安裝的相容深度模型。首次使用時可下載預設模型,或匯入其他相容的 TFLite 模型。</string>
<string name="virtual_aperture_depth_model_description">使用 Depth Anything 3 深度模型,首次使用時需下載。</string>
<string name="gallery_large_aperture_blur_title">大光圈虛化</string>
<string name="gallery_large_aperture_blur_description">模擬大光圈的淺景深背景虛化效果</string>
<string name="gallery_bokeh_style_title">光斑風格</string>
@@ -1062,15 +1062,13 @@
<string name="edit_panel_expand">展開編輯面板</string>
<string name="edit_panel_minimize">最小化編輯面板</string>
<string name="depth_model_download_title">深度模型</string>
<string name="depth_model_download_description">景深虛化功能需要相容的 TFLite 深度模型:包含一個 RGB 影像輸入和一個單通道深度輸出。你可以下載預設的 Depth Anything 3 模型(約 55 MB),也可以匯入其他 TFLite 模型或包含模型的 ZIP 壓縮檔。模型將儲存在 App 的私人目錄中。</string>
<string name="depth_model_download_description">景深虛化功能需要 Depth Anything 3 深度模型(約 55 MB)。模型下載並驗證後將儲存在 App 的私人目錄中。</string>
<string name="depth_model_download_action">下載</string>
<string name="depth_model_import_action">匯入</string>
<string name="depth_model_downloading">正在下載模型…</string>
<string name="depth_model_downloading_progress">正在下載模型… %1$d%%</string>
<string name="depth_model_importing">正在匯入並驗證模型…</string>
<string name="depth_model_installing">正在驗證並安裝模型…</string>
<string name="depth_model_download_failed">模型匯入、下載或驗證失敗,請確認所選檔案或網路連線後重試。</string>
<string name="depth_model_download_ready">相容的深度模型已就緒,可匯入其他模型進行替換。</string>
<string name="depth_model_download_failed">模型下載或驗證失敗,請檢查網路連線後重試。</string>
<string name="depth_model_download_ready">深度模型已就緒。</string>
<string name="depth_model_retry">重試</string>
<string name="depth_model_done">完成</string>
<string name="recipe_tab_palette">調色盤</string>
+4 -6
View File
@@ -1082,7 +1082,7 @@
<string name="virtual_aperture_viewfinder_hint">f/%1$s</string>
<string name="settings_default_virtual_aperture">Default Virtual Aperture</string>
<string name="settings_default_virtual_aperture_description">Automatically enable virtual aperture with the selected f-stop value for new photos.</string>
<string name="virtual_aperture_depth_model_description">Uses the installed compatible depth model. Download the default model or import another compatible TFLite model on first use.</string>
<string name="virtual_aperture_depth_model_description">Uses the Depth Anything 3 depth model. Download it on first use.</string>
<string name="gallery_large_aperture_blur_title">Wide-Aperture Blur</string>
<string name="gallery_large_aperture_blur_description">Simulates the shallow depth of field and background blur of a wide aperture</string>
<string name="gallery_bokeh_style_title">Bokeh style</string>
@@ -1095,15 +1095,13 @@
<string name="edit_panel_expand">Expand editing controls</string>
<string name="edit_panel_minimize">Minimize editing controls</string>
<string name="depth_model_download_title">Depth Model</string>
<string name="depth_model_download_description">Depth-aware blur requires a compatible TFLite depth model with one RGB image input and a single-channel depth output. Download the default Depth Anything 3 model (about 55 MB), or import another TFLite model or a ZIP containing one. The model will be stored privately by the app.</string>
<string name="depth_model_download_description">Depth-aware blur requires the Depth Anything 3 depth model (about 55 MB). It will be downloaded, verified and stored privately by the app.</string>
<string name="depth_model_download_action">Download</string>
<string name="depth_model_import_action">Import</string>
<string name="depth_model_downloading">Downloading model…</string>
<string name="depth_model_downloading_progress">Downloading model… %1$d%%</string>
<string name="depth_model_importing">Importing and verifying model…</string>
<string name="depth_model_installing">Verifying and installing model…</string>
<string name="depth_model_download_failed">The model could not be imported, downloaded, or verified. Check the selected file or your connection and try again.</string>
<string name="depth_model_download_ready">A compatible depth model is ready. You can import another model to replace it.</string>
<string name="depth_model_download_failed">The model could not be downloaded or verified. Check your connection and try again.</string>
<string name="depth_model_download_ready">The depth model is ready.</string>
<string name="depth_model_retry">Retry</string>
<string name="depth_model_done">Done</string>
<string name="ai_denoise_title">AI Deep Denoise</string>
@@ -1,45 +0,0 @@
package com.hinnka.mycamera.ml
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class DepthModelImportFormatTest {
@get:Rule
val temporaryFolder = TemporaryFolder()
@Test
fun detectsTfliteByFlatBufferIdentifierRegardlessOfFileName() {
val file = temporaryFolder.newFile("model.data")
file.writeBytes(byteArrayOf(0, 0, 0, 0, 'T'.code.toByte(), 'F'.code.toByte(), 'L'.code.toByte(), '3'.code.toByte()))
assertEquals(DepthModelImportFormat.TFLITE, detectDepthModelImportFormat(file))
}
@Test
fun detectsSupportedZipSignatures() {
val localEntry = temporaryFolder.newFile("local-entry.bin")
localEntry.writeBytes(byteArrayOf(0x50, 0x4B, 0x03, 0x04))
val emptyArchive = temporaryFolder.newFile("empty-archive.bin")
emptyArchive.writeBytes(byteArrayOf(0x50, 0x4B, 0x05, 0x06))
val spanningArchive = temporaryFolder.newFile("spanning-archive.bin")
spanningArchive.writeBytes(byteArrayOf(0x50, 0x4B, 0x07, 0x08))
assertEquals(DepthModelImportFormat.ZIP, detectDepthModelImportFormat(localEntry))
assertEquals(DepthModelImportFormat.ZIP, detectDepthModelImportFormat(emptyArchive))
assertEquals(DepthModelImportFormat.ZIP, detectDepthModelImportFormat(spanningArchive))
}
@Test
fun rejectsExtensionOnlyAndMismatchedZipSignature() {
val extensionOnly = temporaryFolder.newFile("depth_anything_v2.tflite")
extensionOnly.writeBytes("not a model".toByteArray())
val mismatchedZip = temporaryFolder.newFile("model.zip")
mismatchedZip.writeBytes(byteArrayOf(0x50, 0x4B, 0x03, 0x06))
assertNull(detectDepthModelImportFormat(extensionOnly))
assertNull(detectDepthModelImportFormat(mismatchedZip))
}
}