feat: Photon denoiser
This commit is contained in:
1 parent
bbca4b845d
commit
bef83e201d
60 files changed
+2595
-18827
No files matched your search
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -11,74 +11,6 @@ set(
|
||||
)
|
||||
option(PHOTON_ENABLE_DNG_JXL "Enable Adobe DNG SDK JPEG XL support" OFF)
|
||||
|
||||
set(
|
||||
MGC_DENOISE_CAPSULE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_full_resolution_denoise_capsule.bin"
|
||||
)
|
||||
set(
|
||||
MGC_DENOISE_CAPSULE_SHA256
|
||||
"3ee5c92d2b830448de6270ec0c71ac64a484885a6bd7440d1c53f8695afc55ec"
|
||||
)
|
||||
if(NOT EXISTS "${MGC_DENOISE_CAPSULE}")
|
||||
message(
|
||||
FATAL_ERROR
|
||||
"MGC denoise capsule is missing; regenerate it with "
|
||||
"scripts/research/generate_mgc_denoise_static_asm.py"
|
||||
)
|
||||
endif()
|
||||
file(SHA256 "${MGC_DENOISE_CAPSULE}" MGC_DENOISE_CAPSULE_ACTUAL_SHA256)
|
||||
if(NOT MGC_DENOISE_CAPSULE_ACTUAL_SHA256 STREQUAL MGC_DENOISE_CAPSULE_SHA256)
|
||||
message(FATAL_ERROR "MGC denoise capsule hash mismatch")
|
||||
endif()
|
||||
set(
|
||||
MGC_DENOISE_ASM
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/mgc_full_resolution_denoise_static.S"
|
||||
)
|
||||
configure_file(
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_full_resolution_denoise_static.S.in"
|
||||
"${MGC_DENOISE_ASM}"
|
||||
@ONLY
|
||||
)
|
||||
set_source_files_properties(
|
||||
"${MGC_DENOISE_ASM}"
|
||||
PROPERTIES
|
||||
OBJECT_DEPENDS "${MGC_DENOISE_CAPSULE}"
|
||||
)
|
||||
|
||||
set(
|
||||
MGC_DEMOIRE_CAPSULE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_demoire_capsule.bin"
|
||||
)
|
||||
set(
|
||||
MGC_DEMOIRE_CAPSULE_SHA256
|
||||
"769d656725b445c356b9f3e44341e101806bb201fcd2e5681c0ab92173a68c9a"
|
||||
)
|
||||
if(NOT EXISTS "${MGC_DEMOIRE_CAPSULE}")
|
||||
message(
|
||||
FATAL_ERROR
|
||||
"MGC MeasureMoire capsule is missing; regenerate it with "
|
||||
"scripts/research/generate_mgc_demoire_static_asm.py"
|
||||
)
|
||||
endif()
|
||||
file(SHA256 "${MGC_DEMOIRE_CAPSULE}" MGC_DEMOIRE_CAPSULE_ACTUAL_SHA256)
|
||||
if(NOT MGC_DEMOIRE_CAPSULE_ACTUAL_SHA256 STREQUAL MGC_DEMOIRE_CAPSULE_SHA256)
|
||||
message(FATAL_ERROR "MGC MeasureMoire capsule hash mismatch")
|
||||
endif()
|
||||
set(
|
||||
MGC_DEMOIRE_ASM
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/mgc_demoire_static.S"
|
||||
)
|
||||
configure_file(
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_demoire_static.S.in"
|
||||
"${MGC_DEMOIRE_ASM}"
|
||||
@ONLY
|
||||
)
|
||||
set_source_files_properties(
|
||||
"${MGC_DEMOIRE_ASM}"
|
||||
PROPERTIES
|
||||
OBJECT_DEPENDS "${MGC_DEMOIRE_CAPSULE}"
|
||||
)
|
||||
|
||||
set(
|
||||
MGC_SABRE_CAPSULE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_sabre_resolve_capsule.bin"
|
||||
@@ -373,8 +305,6 @@ set_source_files_properties(
|
||||
# as configure dependencies so a missing output also causes CMake to regenerate it.
|
||||
set_property(
|
||||
DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
|
||||
"${MGC_DENOISE_ASM}"
|
||||
"${MGC_DEMOIRE_ASM}"
|
||||
"${MGC_SABRE_ASM}"
|
||||
"${MGC_SPATIAL_RGB_ASM}"
|
||||
"${MGC_RAISR_ASM}"
|
||||
@@ -479,7 +409,6 @@ add_library(my-native-lib SHARED
|
||||
raw10_unpack.cpp
|
||||
raw10_unpack_jni.cpp
|
||||
raw_legacy_auto_exposure_solver.cpp
|
||||
mgc_strength_map_scaler.cpp
|
||||
mgc_eis_reconstruction_jni.cpp
|
||||
"${MGC_EIS_RECONSTRUCTION_DIR}/mgc_eis_reconstruction.cpp"
|
||||
"${MGC_EIS_RECONSTRUCTION_DIR}/mgc_type18_engine.cpp"
|
||||
@@ -491,11 +420,10 @@ add_library(my-native-lib SHARED
|
||||
yuv_utils.cpp
|
||||
lut_processor.cpp
|
||||
dcp_parser.cpp
|
||||
mgc_denoise_static/mgc_halide_runtime.cpp
|
||||
mgc_denoise_static/mgc_denoise_static.cpp
|
||||
mgc_denoise_static/mgc_full_resolution_denoise_jni.cpp
|
||||
mgc_denoise_static/mgc_sabre_resolve_jni.cpp
|
||||
mgc_denoise_static/mgc_spatial_rgb_merge_jni.cpp
|
||||
mgc_denoise_static/mgc_spatial_strength_jni.cpp
|
||||
mgc_denoise_static/mgc_guided_upsample_jni.cpp
|
||||
mgc_denoise_static/mgc_sharpen_jni.cpp
|
||||
mgc_denoise_static/mgc_raisr_jni.cpp
|
||||
@@ -506,8 +434,6 @@ add_library(my-native-lib SHARED
|
||||
"${MGC_RAISR_ASM}"
|
||||
"${MGC_RAISR_TABLES_ASM}"
|
||||
"${MGC_POLYSHARP_ASM}"
|
||||
"${MGC_DENOISE_ASM}"
|
||||
"${MGC_DEMOIRE_ASM}"
|
||||
"${MGC_SABRE_ASM}"
|
||||
"${MGC_SPATIAL_RGB_ASM}"
|
||||
${LIBRAW_SOURCES}
|
||||
@@ -532,14 +458,6 @@ set_source_files_properties(
|
||||
PROPERTIES COMPILE_OPTIONS "-fno-fast-math;-ffp-contract=off"
|
||||
)
|
||||
|
||||
# Match the former Kotlin Float bilinear path exactly at Q8 rounding boundaries.
|
||||
# This host-side scaler is deliberately independent of the MGC AOT/capsule sources.
|
||||
set_source_files_properties(
|
||||
mgc_strength_map_scaler.cpp
|
||||
PROPERTIES
|
||||
COMPILE_OPTIONS "-fno-fast-math;-ffp-contract=off"
|
||||
)
|
||||
|
||||
# The HDRNet PGTM path rejects non-finite model output and follows the Kotlin
|
||||
# reference interpolation order. Keep those invariants independent of fast math.
|
||||
set_source_files_properties(
|
||||
@@ -580,9 +498,10 @@ set_source_files_properties(
|
||||
COMPILE_OPTIONS "-fno-fast-math;-ffp-contract=off"
|
||||
)
|
||||
|
||||
# MGC host-side tuning and noise-model builders rely on scalar IEEE behavior.
|
||||
# The MGC Halide runtime and AOT wrappers rely on scalar IEEE behavior.
|
||||
# Keep them independent of the target-wide fast-math flags.
|
||||
set_source_files_properties(
|
||||
mgc_denoise_static/mgc_halide_runtime.cpp
|
||||
mgc_denoise_static/mgc_denoise_static.cpp
|
||||
PROPERTIES
|
||||
COMPILE_OPTIONS "-fno-fast-math;-ffp-contract=off"
|
||||
|
||||
Binary file not shown.
@@ -1,490 +0,0 @@
|
||||
/* Generated mechanically from pinned MGC 9.6.080 V24 MeasureMoireS16Halide.
|
||||
* Do not edit; regenerate with
|
||||
* scripts/research/generate_mgc_demoire_static_asm.py.
|
||||
*/
|
||||
|
||||
#if !defined(__aarch64__)
|
||||
#error "MGC MeasureMoire static lift is arm64-only"
|
||||
#endif
|
||||
|
||||
.hidden photon_mgc_halide_error_5ef61ac
|
||||
.hidden photon_mgc_halide_error_5ef6294
|
||||
.hidden photon_mgc_halide_error_5ef636c
|
||||
.hidden photon_mgc_halide_error_5ef63f8
|
||||
.hidden photon_mgc_halide_error_5ef64dc
|
||||
.hidden photon_mgc_halide_error_5ef6568
|
||||
.hidden photon_mgc_halide_error_5ef6600
|
||||
.hidden photon_mgc_halide_error_5ef6794
|
||||
.hidden photon_mgc_halide_error_5ef6a74
|
||||
.hidden photon_mgc_halide_error_5ef6a94
|
||||
.hidden photon_mgc_halide_error_5ef6b6c
|
||||
.hidden photon_mgc_halide_error_5ef6bd8
|
||||
.hidden photon_mgc_halide_error_5ef6c38
|
||||
.hidden photon_mgc_halide_error_5ef6cd0
|
||||
.hidden photon_mgc_halide_do_par_for
|
||||
.hidden photon_mgc_halide_free
|
||||
.hidden photon_mgc_halide_malloc
|
||||
.hidden photon_mgc_halide_trace
|
||||
|
||||
.section .text.photon_mgc.MeasureMoireS16Halide,"ax",@progbits
|
||||
.p2align 12
|
||||
.global photon_mgc_measure_moire_s16_halide
|
||||
.hidden photon_mgc_measure_moire_s16_halide
|
||||
.type photon_mgc_measure_moire_s16_halide, %function
|
||||
photon_mgc_demoire_page_54e1000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x0, 0x100
|
||||
photon_mgc_demoire_address_54e1100:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x100, 0x194
|
||||
bl photon_mgc_halide_malloc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x294, 0x30
|
||||
bl photon_mgc_halide_malloc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x2c4, 0x38
|
||||
bl photon_mgc_halide_malloc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x2fc, 0x138
|
||||
adrp x2, photon_mgc_demoire_page_6b2000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x434, 0x4
|
||||
adrp x3, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x438, 0x404
|
||||
adrp x26, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x83c, 0x16c
|
||||
adrp x25, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x9a8, 0x144
|
||||
bl photon_mgc_halide_malloc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0xaec, 0x4f4
|
||||
photon_mgc_demoire_page_54e2000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0xfe0, 0x638
|
||||
adrp x25, photon_mgc_demoire_page_6b0000
|
||||
adrp x26, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x1618, 0x9c0
|
||||
photon_mgc_demoire_page_54e3000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x1fd8, 0x3f4
|
||||
adrp x25, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x23cc, 0x2c
|
||||
adrp x26, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x23f8, 0x464
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x285c, 0x90
|
||||
bl photon_mgc_halide_malloc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x28ec, 0x308
|
||||
adrp x25, photon_mgc_demoire_page_6b0000
|
||||
adrp x26, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x2bf4, 0x3cc
|
||||
photon_mgc_demoire_page_54e4000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x2fc0, 0x130
|
||||
bl photon_mgc_halide_malloc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x30f0, 0x124
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x3214, 0x1ac
|
||||
adrp x26, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x33c0, 0x178
|
||||
adrp x8, photon_mgc_demoire_page_6b9000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x3538, 0x4b0
|
||||
adrp x8, photon_mgc_demoire_page_6ba000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x39e8, 0x5c4
|
||||
photon_mgc_demoire_page_54e5000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x3fac, 0x694
|
||||
adrp x26, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x4640, 0x5c
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x469c, 0x64
|
||||
bl photon_mgc_halide_malloc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x4700, 0x34
|
||||
bl photon_mgc_halide_malloc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x4734, 0x38
|
||||
bl photon_mgc_halide_malloc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x476c, 0x14c
|
||||
adrp x26, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x48b8, 0x14
|
||||
adrp x24, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x48cc, 0x184
|
||||
adrp x26, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x4a50, 0x11c
|
||||
bl photon_mgc_halide_malloc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x4b6c, 0x24
|
||||
adrp x4, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x4b90, 0x8
|
||||
adrp x5, photon_mgc_demoire_page_6b2000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x4b98, 0x3e8
|
||||
photon_mgc_demoire_page_54e6000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x4f80, 0x550
|
||||
adrp x26, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x54d0, 0x188
|
||||
adrp x4, photon_mgc_demoire_page_6b0000
|
||||
adrp x24, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x5658, 0x8
|
||||
adrp x5, photon_mgc_demoire_page_6b2000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x5660, 0x2e4
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x5944, 0x74
|
||||
bl photon_mgc_halide_malloc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x59b8, 0xe8
|
||||
adrp x21, photon_mgc_demoire_page_6b0000
|
||||
adrp x20, photon_mgc_demoire_page_6b0000
|
||||
adrp x8, photon_mgc_demoire_page_6b2000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x5aa0, 0x208
|
||||
adrp x24, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x5ca8, 0x140
|
||||
bl photon_mgc_halide_malloc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x5de8, 0x120
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x5f08, 0x48
|
||||
photon_mgc_demoire_page_54e7000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x5f50, 0x158
|
||||
adrp x24, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x60a8, 0xac
|
||||
adrp x10, photon_mgc_demoire_page_6b2000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x6154, 0x30
|
||||
adrp x15, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x6184, 0x38
|
||||
adrp x15, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x61bc, 0xf4
|
||||
adrp x0, photon_mgc_demoire_page_6b9000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x62b0, 0x45c
|
||||
adrp x18, photon_mgc_demoire_page_6ba000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x670c, 0x82c
|
||||
photon_mgc_demoire_page_54e8000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x6f38, 0x394
|
||||
adrp x24, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x72cc, 0x44
|
||||
adrp x24, photon_mgc_demoire_page_6b0000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7310, 0x50
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7360, 0x10
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7370, 0xc
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x737c, 0xc
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7388, 0x40
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x73c8, 0x28
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x73f0, 0x2c
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x741c, 0x28
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7444, 0x28
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x746c, 0x28
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7494, 0x24
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x74b8, 0x3c
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x74f4, 0xc
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7500, 0x14
|
||||
bl photon_mgc_halide_error_5ef6a74
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7514, 0x38
|
||||
bl photon_mgc_halide_error_5ef6a74
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x754c, 0x38
|
||||
bl photon_mgc_halide_error_5ef6a74
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7584, 0x38
|
||||
bl photon_mgc_halide_error_5ef6a74
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x75bc, 0x28
|
||||
bl photon_mgc_halide_free
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x75e4, 0x40
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7624, 0x4
|
||||
adrp x2, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7628, 0x4
|
||||
adrp x3, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x762c, 0xc
|
||||
bl photon_mgc_halide_error_5ef6c38
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7638, 0x8
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7640, 0x4
|
||||
adrp x2, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7644, 0x4
|
||||
adrp x3, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7648, 0x4
|
||||
bl photon_mgc_halide_error_5ef6c38
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x764c, 0x4
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7650, 0x4
|
||||
adrp x2, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7654, 0x4
|
||||
adrp x3, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7658, 0x10
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7668, 0x4
|
||||
adrp x2, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x766c, 0x4
|
||||
adrp x3, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7670, 0x8
|
||||
bl photon_mgc_halide_error_5ef6c38
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7678, 0x18
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7690, 0x4
|
||||
adrp x2, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7694, 0x4
|
||||
adrp x4, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7698, 0x20
|
||||
bl photon_mgc_halide_error_5ef6cd0
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x76b8, 0xc
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x76c4, 0x4
|
||||
adrp x2, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x76c8, 0xc
|
||||
adrp x4, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x76d4, 0x18
|
||||
bl photon_mgc_halide_error_5ef6cd0
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x76ec, 0xc
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x76f8, 0xc
|
||||
bl photon_mgc_halide_error_5ef64dc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7704, 0x10
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7714, 0x20
|
||||
bl photon_mgc_halide_error_5ef64dc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7734, 0x10
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7744, 0x14
|
||||
bl photon_mgc_halide_error_5ef64dc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7758, 0x20
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7778, 0x10
|
||||
bl photon_mgc_halide_error_5ef64dc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7788, 0x4
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x778c, 0x4
|
||||
adrp x2, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7790, 0x4
|
||||
adrp x3, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7794, 0x8
|
||||
bl photon_mgc_halide_error_5ef6c38
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x779c, 0xc
|
||||
bl photon_mgc_halide_error_5ef6a74
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x77a8, 0x20
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x77c8, 0x20
|
||||
bl photon_mgc_halide_error_5ef64dc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x77e8, 0xc
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x77f4, 0x18
|
||||
bl photon_mgc_halide_error_5ef64dc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x780c, 0x1c
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7828, 0xc
|
||||
bl photon_mgc_halide_error_5ef64dc
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7834, 0x4
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7838, 0x4
|
||||
adrp x2, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x783c, 0x4
|
||||
adrp x3, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7840, 0x8
|
||||
bl photon_mgc_halide_error_5ef6c38
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7848, 0x24
|
||||
bl photon_mgc_halide_error_5ef6a74
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x786c, 0x3c
|
||||
bl photon_mgc_halide_error_5ef6a74
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x78a8, 0x24
|
||||
bl photon_mgc_halide_error_5ef6a74
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x78cc, 0x1c
|
||||
bl photon_mgc_halide_error_5ef6a74
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x78e8, 0x34
|
||||
photon_mgc_demoire_address_54e8afc:
|
||||
photon_mgc_measure_moire_s16_halide:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x791c, 0x370
|
||||
adrp x18, photon_mgc_demoire_page_6aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7c8c, 0xbc
|
||||
adrp x9, photon_mgc_demoire_page_6aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7d48, 0x88
|
||||
adrp x15, photon_mgc_demoire_page_6aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7dd0, 0x44
|
||||
photon_mgc_demoire_page_54e9000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x7e14, 0x330
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8144, 0x44
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8188, 0x44
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x81cc, 0x34
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8200, 0x3c
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x823c, 0x28
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8264, 0x2c
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8290, 0x34
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x82c4, 0x4
|
||||
adrp x3, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x82c8, 0x1c
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x82e4, 0x30
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8314, 0x2a4
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x85b8, 0x30
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x85e8, 0x28
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8610, 0x30
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8640, 0x24
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8664, 0x24
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8688, 0x28
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x86b0, 0x38
|
||||
adrp x8, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x86e8, 0x4
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x86ec, 0x20
|
||||
bl photon_mgc_halide_trace
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x870c, 0xd0
|
||||
adrp x14, photon_mgc_demoire_page_6a8000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x87dc, 0x128
|
||||
adrp x1, photon_mgc_demoire_page_6152000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8904, 0x58
|
||||
bl photon_mgc_halide_do_par_for
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x895c, 0x14
|
||||
adrp x8, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8970, 0x4
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8974, 0x20
|
||||
bl photon_mgc_halide_trace
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8994, 0x30
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x89c4, 0x8
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x89cc, 0xc
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x89d8, 0x2c
|
||||
b photon_mgc_halide_error_5ef6a94
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8a04, 0x4
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8a08, 0x4
|
||||
adrp x2, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8a0c, 0x38
|
||||
b photon_mgc_halide_error_5ef61ac
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8a44, 0x4
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8a48, 0x10
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8a58, 0x8
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8a60, 0x18
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8a78, 0x24
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8a9c, 0x18
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8ab4, 0x18
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8acc, 0x18
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8ae4, 0x10
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8af4, 0x30
|
||||
b photon_mgc_halide_error_5ef636c
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8b24, 0x8
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8b2c, 0x34
|
||||
b photon_mgc_halide_error_5ef6294
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8b60, 0x10
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8b70, 0x10
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8b80, 0x10
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8b90, 0x8
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8b98, 0x30
|
||||
b photon_mgc_halide_error_5ef6b6c
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8bc8, 0x10
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8bd8, 0xc
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8be4, 0x10
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8bf4, 0x10
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8c04, 0x38
|
||||
b photon_mgc_halide_error_5ef6600
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8c3c, 0x38
|
||||
b photon_mgc_halide_error_5ef64dc
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8c74, 0x8
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8c7c, 0x8
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8c84, 0x30
|
||||
b photon_mgc_halide_error_5ef6bd8
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8cb4, 0x8
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8cbc, 0x20
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8cdc, 0x14
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8cf0, 0x14
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
photon_mgc_demoire_page_54ea000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8d04, 0x3c
|
||||
b photon_mgc_halide_error_5ef63f8
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8d40, 0x8
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8d48, 0x30
|
||||
b photon_mgc_halide_error_5ef6568
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8d78, 0x4
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8d7c, 0x4
|
||||
adrp x3, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8d80, 0xc
|
||||
adrp x1, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8d8c, 0x4
|
||||
adrp x3, photon_mgc_demoire_page_10aa000
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8d90, 0x34
|
||||
b photon_mgc_halide_error_5ef6794
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x8dc4, 0xf20
|
||||
|
||||
.section .rodata.photon_mgc.demoire_page_6a8000,"a",@progbits
|
||||
.p2align 12
|
||||
photon_mgc_demoire_page_6a8000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x9ce4, 0x1000
|
||||
|
||||
.section .rodata.photon_mgc.demoire_page_6aa000,"a",@progbits
|
||||
.p2align 12
|
||||
photon_mgc_demoire_page_6aa000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0xace4, 0x1000
|
||||
|
||||
.section .rodata.photon_mgc.demoire_page_6b0000,"a",@progbits
|
||||
.p2align 12
|
||||
photon_mgc_demoire_page_6b0000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0xbce4, 0x1000
|
||||
|
||||
.section .rodata.photon_mgc.demoire_page_6b2000,"a",@progbits
|
||||
.p2align 12
|
||||
photon_mgc_demoire_page_6b2000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0xcce4, 0x1000
|
||||
|
||||
.section .rodata.photon_mgc.demoire_page_6b9000,"a",@progbits
|
||||
.p2align 12
|
||||
photon_mgc_demoire_page_6b9000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0xdce4, 0x1000
|
||||
|
||||
.section .rodata.photon_mgc.demoire_page_6ba000,"a",@progbits
|
||||
.p2align 12
|
||||
photon_mgc_demoire_page_6ba000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0xece4, 0x1000
|
||||
|
||||
.section .rodata.photon_mgc.demoire_page_10aa000,"a",@progbits
|
||||
.p2align 12
|
||||
photon_mgc_demoire_page_10aa000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0xfce4, 0x1000
|
||||
|
||||
.section .data.rel.ro.photon_mgc.demoire_page_6152000,"aw",@progbits
|
||||
.p2align 12
|
||||
photon_mgc_demoire_page_6152000:
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x10ce4, 0xb10
|
||||
.xword photon_mgc_demoire_address_54e1100
|
||||
.incbin "@MGC_DEMOIRE_CAPSULE@", 0x117f4, 0x4e8
|
||||
|
||||
.section .note.GNU-stack,"",@progbits
|
||||
File diff suppressed because it is too large.
Load diff
@@ -4,219 +4,11 @@
|
||||
|
||||
namespace photon::mgc_denoise {
|
||||
|
||||
struct DenoiseNoiseBuffers {
|
||||
float read[8] = {};
|
||||
float shot[8] = {};
|
||||
float quadratic[8] = {};
|
||||
float outlier_distance[5] = {};
|
||||
float revert_factor[5] = {};
|
||||
};
|
||||
|
||||
struct ChromaDenoiseNoiseBuffers {
|
||||
// CompleteS16 consumes one scalar [level=4, branch=2] quadratic/shot table with branch
|
||||
// stride 12, while retaining [level=4, channel=3, branch=2] read variance. Keeping the
|
||||
// original 24-value backing layout preserves those exact sliced strides (1, 12).
|
||||
float quadratic[24] = {};
|
||||
float shot[24] = {};
|
||||
float read[24] = {};
|
||||
uint8_t outlier_threshold[8] = {};
|
||||
};
|
||||
|
||||
enum class SpatialStrengthInputLayout {
|
||||
Bayer = 0,
|
||||
Rgb = 1,
|
||||
};
|
||||
|
||||
struct SpatialStrengthResult {
|
||||
// Bayer Halide NoiseModel tuple: .0 = read variance,
|
||||
// .1 = shot coefficient. The convenience NoiseModel constructor at
|
||||
// 0x5e959c8 prepends the zero quadratic span before forwarding them.
|
||||
float output_noise_model_0[3] = {};
|
||||
float output_noise_model_1[3] = {};
|
||||
float output_weights_sum_total_diag_0[3] = {};
|
||||
float output_weights_sum_total_diag_1[3] = {};
|
||||
};
|
||||
|
||||
/**
|
||||
* Reproduces CreateLumaDenoiseNoiseBuffers for one luma noise channel.
|
||||
* correlation is MGC's 128-bin normalized power correlation spectrum. A
|
||||
* single uncorrelated frame is represented by 128 ones. A uniformly scaled
|
||||
* spectrum contributes the square of that scale to the separable 2D noise
|
||||
* energy; an all-zero spectrum therefore produces zero noise at every level.
|
||||
*/
|
||||
bool BuildNoiseBuffers(
|
||||
float read_noise,
|
||||
float shot_noise,
|
||||
float quadratic_noise,
|
||||
const float correlation[128],
|
||||
float response_offset,
|
||||
float response_cosine_offset,
|
||||
const float strength[5],
|
||||
const float outlier_distance[5],
|
||||
const float revert_factor[5],
|
||||
DenoiseNoiseBuffers* output);
|
||||
|
||||
/**
|
||||
* Reproduces CreateChromaDenoiseNoiseModelBuffers. Input coefficients are
|
||||
* already transformed into MGC's Y/Cb/Cr domain.
|
||||
*/
|
||||
bool BuildChromaNoiseBuffers(
|
||||
const float read_noise[3],
|
||||
float shot_noise,
|
||||
float quadratic_noise,
|
||||
const float correlation[128],
|
||||
float response_offset,
|
||||
float response_cosine_offset,
|
||||
const float strength[5],
|
||||
const float outlier_threshold[5],
|
||||
ChromaDenoiseNoiseBuffers* output);
|
||||
|
||||
/**
|
||||
* Runs the original ComputeDenoiseStrengthMapsU16Halide kernel.
|
||||
*
|
||||
* gain_map is [height][width][4] interleaved Camera2 R/Ge/Go/B gain data.
|
||||
* output is three planar U16 channels: strength, strength*lumaGain and
|
||||
* strength*lumaGain^2. origin_x/origin_y place a local tile in the full
|
||||
* quarter-resolution strength coordinate system so gain-map sampling remains
|
||||
* identical to a full-frame dispatch.
|
||||
*/
|
||||
int ComputeStrengthMap(
|
||||
const uint16_t* input,
|
||||
int width,
|
||||
int height,
|
||||
int origin_x,
|
||||
int origin_y,
|
||||
const float* gain_map,
|
||||
int gain_width,
|
||||
int gain_height,
|
||||
float sample_rate_x,
|
||||
float sample_rate_y,
|
||||
uint16_t* output);
|
||||
|
||||
/**
|
||||
* Runs MGC's exact Spatial Compute*NoiseModelF32TileSize16 pipeline.
|
||||
*
|
||||
* fused_fixed16 is signed Q14. Bayer uses [quadX,quadY,phase] with positional
|
||||
* phase order 00/10/01/11; RGB uses planar [x,y,rgb]. Alignment is planar
|
||||
* [x,y,frame,xy], rejection is [x,y,frame], and per-frame RGB noise
|
||||
* coefficients are planar [frame,rgb].
|
||||
*/
|
||||
int ComputeSpatialStrengthMap(
|
||||
SpatialStrengthInputLayout layout,
|
||||
const int16_t* fused_fixed16,
|
||||
int width,
|
||||
int height,
|
||||
int cfa_pattern,
|
||||
const float* alignment,
|
||||
int alignment_width,
|
||||
int alignment_height,
|
||||
const uint8_t* rejection,
|
||||
int rejection_width,
|
||||
int rejection_height,
|
||||
int frame_count,
|
||||
const float* input_read_noise,
|
||||
const float* input_shot_noise,
|
||||
const float* frame_weights,
|
||||
const float* kernel_sigmas,
|
||||
float rejected_denoise_multiplier,
|
||||
uint16_t* output_strength_q8,
|
||||
SpatialStrengthResult* diagnostics);
|
||||
|
||||
/** Runs the statically linked RgbRawToYuv1xS16 with neutral corrections. */
|
||||
int RunRgbRawToYuv(
|
||||
const uint16_t* input,
|
||||
int width,
|
||||
int height,
|
||||
int16_t* output);
|
||||
|
||||
/**
|
||||
* Runs MGC's default standard-Bayer RawToYuv path on normalized unsigned-Q14
|
||||
* input packed as four planar 2x2 Bayer-position channels. Channel gains use
|
||||
* semantic [R,G1,G2,B] order. cfa_pattern uses Camera2's 0..3 enumeration;
|
||||
* the implementation maps it to MGC's differently ordered BayerPattern enum.
|
||||
*/
|
||||
int RunDefaultBayerRawToYuv(
|
||||
const uint16_t* packed_input,
|
||||
int width,
|
||||
int height,
|
||||
int cfa_pattern,
|
||||
const float channel_gains[4],
|
||||
const float* gain_map,
|
||||
int gain_map_width,
|
||||
int gain_map_height,
|
||||
float gain_map_sample_rate_x,
|
||||
float gain_map_sample_rate_y,
|
||||
int16_t* output);
|
||||
|
||||
/**
|
||||
* Applies the exact default Bayer demosaic NoiseModel remap and correlation
|
||||
* composition performed by PrepareFullResolutionDenoiseNoiseModel.
|
||||
* Coefficients must already include channel gains and the full-resolution
|
||||
* NoiseModel Scale(2).
|
||||
*/
|
||||
bool PrepareDefaultBayerDenoiseNoiseModel(
|
||||
const float input_read[3],
|
||||
const float input_shot[3],
|
||||
const float input_quadratic[3],
|
||||
const float input_correlation[128],
|
||||
float output_read[3],
|
||||
float output_shot[3],
|
||||
float output_quadratic[3],
|
||||
float output_correlation[128],
|
||||
float* correlation_mean);
|
||||
|
||||
/**
|
||||
* Runs MGC's standard-Bayer MeasureMoireS16Halide stage. The input is the
|
||||
* full-resolution signed-Q14 Y plane emitted by RawToYuv. Both strength maps
|
||||
* are three planar unsigned-Q8 channels at quarter resolution.
|
||||
*/
|
||||
int RunMeasureMoireS16(
|
||||
const int16_t* input,
|
||||
int width,
|
||||
int height,
|
||||
const uint16_t* strength_map,
|
||||
int strength_width,
|
||||
int strength_height,
|
||||
uint16_t* output_strength_map);
|
||||
|
||||
/** Runs the complete four-level S16 chroma pyramid used by MGC. */
|
||||
int RunChromaDenoise(
|
||||
const int16_t* input,
|
||||
int width,
|
||||
int height,
|
||||
const uint16_t* strength_map,
|
||||
int strength_width,
|
||||
int strength_height,
|
||||
const ChromaDenoiseNoiseBuffers& noise,
|
||||
int16_t* output);
|
||||
|
||||
/**
|
||||
* Runs the exact statically linked PecanLumaDenoise S16 kernel recovered from
|
||||
* RunFullResolutionDenoise.
|
||||
*/
|
||||
int RunPecan(
|
||||
const uint16_t* strength_map,
|
||||
int strength_width,
|
||||
int strength_height,
|
||||
const DenoiseNoiseBuffers& noise,
|
||||
const int16_t* input,
|
||||
int width,
|
||||
int height,
|
||||
int16_t* output);
|
||||
|
||||
/** Runs the statically linked YuvToRgbS16 kernel on planar S16 data. */
|
||||
int RunYuvToRgb(
|
||||
const int16_t* input,
|
||||
int width,
|
||||
int height,
|
||||
int16_t* output);
|
||||
|
||||
/**
|
||||
* Runs MGC 9.6.080's exact SharpenTo16BitHalide FinishRaw kernel.
|
||||
*
|
||||
* input_yuv must be the tone-mapped U12 YUV emitted by ProcessLowFrequency
|
||||
* and restored by GuidedUpsample. It is not compatible with RawToYuv or the
|
||||
* full-resolution denoiser's signed-Q14 linear YUV boundary.
|
||||
* and restored by GuidedUpsample, not the guide's signed-Q14 linear YUV.
|
||||
* Output storage must accommodate width * round_up(height, 2) * 3 uint16_t
|
||||
* values for the AOT's two-row tail; only the first height rows are consumed.
|
||||
*/
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -77,4 +77,26 @@ inline bool GuidedFloatRgbaToLinearYuv(const float *rgba, int width, int height,
|
||||
return invalid == 0;
|
||||
}
|
||||
|
||||
// White-box YuvToRgbS16 (MGC 9.6.080 V24, photon_mgc_yuv_to_rgb_s16): the AOT's
|
||||
// entry fixes four Q-format coefficients and its vector body computes, per pixel,
|
||||
// R = Y + rshr(V * 25802, 15)
|
||||
// G = Y + rshr(V * -15340 + U * -8658, 16)
|
||||
// B = Y + rshr(U * 21442, 14)
|
||||
// with rshr the signed rounding shift (ties toward +infinity) on the int32 product
|
||||
// and a saturating narrow to int16. It inverts the matrix above. Verified bit-exact
|
||||
// against the AOT body under emulation on edge grids and full-range random planes.
|
||||
inline void GuidedLinearYuvToRgb(const int16_t *yuv, size_t count, int16_t *rgb) {
|
||||
const int16_t *y_plane = yuv, *u_plane = yuv + count, *v_plane = yuv + count * 2;
|
||||
const auto saturate = [](int32_t v) {
|
||||
return int16_t(std::clamp<int32_t>(v, INT16_MIN, INT16_MAX));
|
||||
};
|
||||
#pragma omp parallel for schedule(static) num_threads(4)
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
const int32_t y = y_plane[i], u = u_plane[i], v = v_plane[i];
|
||||
rgb[i] = saturate(y + ((v * 25802 + (1 << 14)) >> 15));
|
||||
rgb[count + i] = saturate(y + ((v * -15340 + u * -8658 + (1 << 15)) >> 16));
|
||||
rgb[count * 2 + i] = saturate(y + ((u * 21442 + (1 << 13)) >> 14));
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace photon::mgc_denoise
|
||||
@@ -79,8 +79,7 @@ Java_com_hinnka_mycamera_raw_MgcGuidedUpsample_nativePrepare(
|
||||
// The low color branch starts before CCM/DCP/tone; never downsample an
|
||||
// encoded JPEG.
|
||||
std::vector<int16_t> low_rgb(ln * 3);
|
||||
if (RunYuvToRgb(low.data(), pw / scale, ph / scale, low_rgb.data()) != 0)
|
||||
return 0;
|
||||
GuidedLinearYuvToRgb(low.data(), ln, low_rgb.data());
|
||||
const auto low_color = Clock::now();
|
||||
#pragma omp parallel for schedule(static) num_threads(4)
|
||||
for (size_t i = 0; i < ln; ++i) {
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
// Shared Halide runtime for the lifted MGC AOT capsules (docs/photon-multiscale-denoise.md §15):
|
||||
// allocation, tracing, parallel dispatch and the validation-error hooks the capsules call.
|
||||
#include "mgc_raisr_executor.h"
|
||||
#include "mgc_raisr_timing.h"
|
||||
|
||||
#include <android/log.h>
|
||||
#include <pthread.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <sys/types.h>
|
||||
|
||||
namespace photon::mgc_denoise {
|
||||
namespace {
|
||||
|
||||
constexpr char kTag[] = "PLog_MgcHalideRuntime";
|
||||
|
||||
using HalideTask = int (*)(void*, int, uint8_t*);
|
||||
|
||||
void* HalideMalloc(void*, size_t size) {
|
||||
void* result = nullptr;
|
||||
if (posix_memalign(&result, 128, std::max<size_t>(size, 1)) != 0) {
|
||||
return nullptr;
|
||||
}
|
||||
#if defined(MGC_DENOISE_FORCE_SERIAL)
|
||||
__android_log_print(
|
||||
ANDROID_LOG_INFO,
|
||||
kTag,
|
||||
"probe HalideMalloc size=%zu result=%p",
|
||||
size,
|
||||
result);
|
||||
#endif
|
||||
return result;
|
||||
}
|
||||
|
||||
void HalideFree(void*, void* pointer) {
|
||||
free(pointer);
|
||||
}
|
||||
|
||||
uintptr_t HalideTrace(
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct ParallelJob {
|
||||
void* user_context;
|
||||
HalideTask task;
|
||||
int minimum;
|
||||
int size;
|
||||
uint8_t* closure;
|
||||
std::atomic<int> next{0};
|
||||
std::atomic<int> first_error{0};
|
||||
};
|
||||
|
||||
void* RunParallelJob(void* opaque) {
|
||||
auto* job = static_cast<ParallelJob*>(opaque);
|
||||
for (;;) {
|
||||
const int offset = job->next.fetch_add(1, std::memory_order_relaxed);
|
||||
if (offset >= job->size) break;
|
||||
const int result =
|
||||
job->task(job->user_context, job->minimum + offset, job->closure);
|
||||
if (result != 0) {
|
||||
int expected = 0;
|
||||
job->first_error.compare_exchange_strong(
|
||||
expected,
|
||||
result,
|
||||
std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
int HalideDoParFor(
|
||||
void* user_context,
|
||||
HalideTask task,
|
||||
int minimum,
|
||||
int size,
|
||||
uint8_t* closure) {
|
||||
if (size <= 0) return 0;
|
||||
if (photon_raisr::active_timing) ++photon_raisr::active_timing->parallel_calls;
|
||||
if (photon_raisr::active_executor) {
|
||||
return photon_raisr::active_executor->Run(user_context, task, minimum, size, closure);
|
||||
}
|
||||
#if defined(MGC_DENOISE_FORCE_SERIAL)
|
||||
__android_log_print(
|
||||
ANDROID_LOG_INFO,
|
||||
kTag,
|
||||
"probe HalideDoParFor task=%p min=%d size=%d closure=%p",
|
||||
reinterpret_cast<void*>(task),
|
||||
minimum,
|
||||
size,
|
||||
closure);
|
||||
#endif
|
||||
ParallelJob job{user_context, task, minimum, size, closure};
|
||||
long online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
|
||||
online_cpus = std::max<long>(online_cpus, 1);
|
||||
#if defined(MGC_DENOISE_FORCE_SERIAL)
|
||||
online_cpus = 1;
|
||||
#endif
|
||||
const int worker_count =
|
||||
std::min<int>(std::min<long>(online_cpus, size), 16);
|
||||
pthread_t workers[15] = {};
|
||||
int created = 0;
|
||||
{
|
||||
photon_raisr::ScopedTiming timer(&photon_raisr::Timing::thread_create);
|
||||
for (int index = 1; index < worker_count; ++index) {
|
||||
if (pthread_create(
|
||||
&workers[created],
|
||||
nullptr,
|
||||
RunParallelJob,
|
||||
&job) != 0) {
|
||||
break;
|
||||
}
|
||||
++created;
|
||||
}
|
||||
}
|
||||
if (photon_raisr::active_timing) photon_raisr::active_timing->workers_created += created;
|
||||
RunParallelJob(&job);
|
||||
photon_raisr::ScopedTiming join_timer(&photon_raisr::Timing::thread_join);
|
||||
for (int index = 0; index < created; ++index) {
|
||||
pthread_join(workers[index], nullptr);
|
||||
}
|
||||
return job.first_error.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
template <uintptr_t Target>
|
||||
uintptr_t HalideValidationError(
|
||||
uintptr_t argument0,
|
||||
uintptr_t argument1,
|
||||
uintptr_t argument2,
|
||||
uintptr_t argument3,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR,
|
||||
kTag,
|
||||
"MGC Halide validation target=0x%zx args=[0x%zx,0x%zx,0x%zx,0x%zx]",
|
||||
static_cast<size_t>(Target),
|
||||
static_cast<size_t>(argument0),
|
||||
static_cast<size_t>(argument1),
|
||||
static_cast<size_t>(argument2),
|
||||
static_cast<size_t>(argument3));
|
||||
return Target;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" __attribute__((visibility("hidden"))) void*
|
||||
photon_mgc_halide_malloc(void* user_context, size_t size) {
|
||||
return HalideMalloc(user_context, size);
|
||||
}
|
||||
|
||||
extern "C" __attribute__((visibility("hidden"))) void
|
||||
photon_mgc_halide_free(void* user_context, void* pointer) {
|
||||
HalideFree(user_context, pointer);
|
||||
}
|
||||
|
||||
extern "C" __attribute__((visibility("hidden"))) uintptr_t
|
||||
photon_mgc_halide_trace(
|
||||
uintptr_t argument0,
|
||||
uintptr_t argument1,
|
||||
uintptr_t argument2,
|
||||
uintptr_t argument3,
|
||||
uintptr_t argument4,
|
||||
uintptr_t argument5,
|
||||
uintptr_t argument6,
|
||||
uintptr_t argument7,
|
||||
uintptr_t argument8,
|
||||
uintptr_t argument9,
|
||||
uintptr_t argument10,
|
||||
uintptr_t argument11) {
|
||||
return HalideTrace(
|
||||
argument0,
|
||||
argument1,
|
||||
argument2,
|
||||
argument3,
|
||||
argument4,
|
||||
argument5,
|
||||
argument6,
|
||||
argument7,
|
||||
argument8,
|
||||
argument9,
|
||||
argument10,
|
||||
argument11);
|
||||
}
|
||||
|
||||
extern "C" __attribute__((visibility("hidden"))) int
|
||||
photon_mgc_halide_do_par_for(
|
||||
void* user_context,
|
||||
HalideTask task,
|
||||
int minimum,
|
||||
int size,
|
||||
uint8_t* closure) {
|
||||
return HalideDoParFor(user_context, task, minimum, size, closure);
|
||||
}
|
||||
|
||||
#define PHOTON_MGC_DEFINE_HALIDE_ERROR(address) \
|
||||
extern "C" __attribute__((visibility("hidden"))) uintptr_t \
|
||||
photon_mgc_halide_error_##address( \
|
||||
uintptr_t argument0, \
|
||||
uintptr_t argument1, \
|
||||
uintptr_t argument2, \
|
||||
uintptr_t argument3, \
|
||||
uintptr_t argument4, \
|
||||
uintptr_t argument5, \
|
||||
uintptr_t argument6, \
|
||||
uintptr_t argument7) { \
|
||||
return HalideValidationError<0x##address>( \
|
||||
argument0, \
|
||||
argument1, \
|
||||
argument2, \
|
||||
argument3, \
|
||||
argument4, \
|
||||
argument5, \
|
||||
argument6, \
|
||||
argument7); \
|
||||
}
|
||||
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef61ac)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef64dc)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6568)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6600)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6794)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6a74)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6a94)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6b6c)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6bd8)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ef6c38)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(2055170)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(38a3740)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(38a92e8)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f94b18)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f94c0c)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f94c78)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f94d60)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f94e38)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f94ec4)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f94fa8)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f95034)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f950cc)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f95260)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f95540)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f95560)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f95638)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f956a4)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ff6938)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ff8944)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5ff89a0)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f95158)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f95704)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f9579c)
|
||||
PHOTON_MGC_DEFINE_HALIDE_ERROR(5f95a4c)
|
||||
|
||||
#undef PHOTON_MGC_DEFINE_HALIDE_ERROR
|
||||
|
||||
extern "C" __attribute__((visibility("hidden"))) uintptr_t
|
||||
photon_mgc_halide_error_5ef63f8(
|
||||
uintptr_t user_context,
|
||||
uintptr_t buffer_name,
|
||||
uintptr_t dimension,
|
||||
uintptr_t minimum_touched,
|
||||
uintptr_t maximum_touched,
|
||||
uintptr_t minimum_valid,
|
||||
uintptr_t maximum_valid,
|
||||
uintptr_t) {
|
||||
const char* name = reinterpret_cast<const char*>(buffer_name);
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR,
|
||||
kTag,
|
||||
"MGC Halide access out of bounds name=%s dimension=%zu "
|
||||
"touched=[%zd,%zd] valid=[%zd,%zd] userContext=%p",
|
||||
name != nullptr ? name : "<null>",
|
||||
static_cast<size_t>(dimension),
|
||||
static_cast<ssize_t>(minimum_touched),
|
||||
static_cast<ssize_t>(maximum_touched),
|
||||
static_cast<ssize_t>(minimum_valid),
|
||||
static_cast<ssize_t>(maximum_valid),
|
||||
reinterpret_cast<void*>(user_context));
|
||||
return static_cast<uintptr_t>(0x5ef63f8);
|
||||
}
|
||||
|
||||
extern "C" __attribute__((visibility("hidden"))) uintptr_t
|
||||
photon_mgc_halide_error_5ef636c(
|
||||
uintptr_t user_context,
|
||||
uintptr_t buffer_name,
|
||||
uintptr_t actual_dimensions,
|
||||
uintptr_t expected_dimensions,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t) {
|
||||
const char* name = reinterpret_cast<const char*>(buffer_name);
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR,
|
||||
kTag,
|
||||
"MGC Halide buffer dimension mismatch name=%s actual=%zu expected=%zu userContext=%p",
|
||||
name != nullptr ? name : "<null>",
|
||||
static_cast<size_t>(actual_dimensions),
|
||||
static_cast<size_t>(expected_dimensions),
|
||||
reinterpret_cast<void*>(user_context));
|
||||
return static_cast<uintptr_t>(0x5ef636c);
|
||||
}
|
||||
|
||||
extern "C" __attribute__((visibility("hidden"))) uintptr_t
|
||||
photon_mgc_halide_error_5ef6294(
|
||||
uintptr_t user_context,
|
||||
uintptr_t buffer_name,
|
||||
uintptr_t actual_type,
|
||||
uintptr_t expected_type,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t,
|
||||
uintptr_t) {
|
||||
(void)user_context;
|
||||
const char* name = reinterpret_cast<const char*>(buffer_name);
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR,
|
||||
kTag,
|
||||
"MGC Halide buffer type mismatch name=%s expected=0x%zx "
|
||||
"actual=0x%zx",
|
||||
name != nullptr ? name : "<null>",
|
||||
static_cast<size_t>(expected_type),
|
||||
static_cast<size_t>(actual_type));
|
||||
// The original helper ABI is (user_context, name, actual, expected).
|
||||
// It returns Halide's halide_error_code_bad_type (-3).
|
||||
return static_cast<uintptr_t>(static_cast<intptr_t>(-3));
|
||||
}
|
||||
|
||||
} // namespace photon::mgc_denoise
|
||||
@@ -103,35 +103,6 @@ bool CheckedProduct(std::initializer_list<int64_t> factors, int64_t* result) {
|
||||
return true;
|
||||
}
|
||||
|
||||
float HalfToFloat(uint16_t value) {
|
||||
const uint32_t sign = static_cast<uint32_t>(value & 0x8000u) << 16u;
|
||||
uint32_t exponent = (value >> 10u) & 0x1fu;
|
||||
uint32_t mantissa = value & 0x03ffu;
|
||||
uint32_t encoded = 0;
|
||||
if (exponent == 0) {
|
||||
if (mantissa == 0) {
|
||||
encoded = sign;
|
||||
} else {
|
||||
int shift = 0;
|
||||
while ((mantissa & 0x0400u) == 0) {
|
||||
mantissa <<= 1u;
|
||||
++shift;
|
||||
}
|
||||
mantissa &= 0x03ffu;
|
||||
encoded = sign |
|
||||
(static_cast<uint32_t>(127 - 14 - shift) << 23u) |
|
||||
(mantissa << 13u);
|
||||
}
|
||||
} else if (exponent == 0x1fu) {
|
||||
encoded = sign | 0x7f800000u | (mantissa << 13u);
|
||||
} else {
|
||||
encoded = sign | ((exponent + 127u - 15u) << 23u) | (mantissa << 13u);
|
||||
}
|
||||
float result = 0.0f;
|
||||
std::memcpy(&result, &encoded, sizeof(result));
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Exact generated ABI at MGC 9.7.047 V25 libgcastartup.so+0x371990c.
|
||||
@@ -404,24 +375,3 @@ Java_com_hinnka_mycamera_processor_MgcSpatialRgbMerger_nativeMerge(
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jint JNICALL
|
||||
Java_com_hinnka_mycamera_processor_MgcSpatialRgbMerger_nativeConvertPlanarF16ToFixed16(
|
||||
JNIEnv* env,
|
||||
jobject,
|
||||
jobject buffer,
|
||||
jint sample_count) {
|
||||
if (buffer == nullptr || sample_count <= 0) return -1;
|
||||
auto* samples = static_cast<uint16_t*>(env->GetDirectBufferAddress(buffer));
|
||||
const int64_t required_bytes =
|
||||
static_cast<int64_t>(sample_count) * static_cast<int64_t>(sizeof(uint16_t));
|
||||
if (samples == nullptr || env->GetDirectBufferCapacity(buffer) < required_bytes) return -1;
|
||||
auto* fixed16 = reinterpret_cast<int16_t*>(samples);
|
||||
for (int index = 0; index < sample_count; ++index) {
|
||||
const float sample = HalfToFloat(samples[index]);
|
||||
const float finite_sample = std::isfinite(sample) ? sample : 0.0f;
|
||||
fixed16[index] = static_cast<int16_t>(std::lrintf(
|
||||
std::clamp(finite_sample, 0.0f, 32767.0f)));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,295 +0,0 @@
|
||||
#include "mgc_denoise_static.h"
|
||||
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr char kTag[] = "PLog_MgcSpatialStrength";
|
||||
|
||||
bool CopyFloatArray(
|
||||
JNIEnv* env,
|
||||
jfloatArray source,
|
||||
int expected,
|
||||
std::vector<float>* output) {
|
||||
if (source == nullptr || expected <= 0 ||
|
||||
env->GetArrayLength(source) != expected) {
|
||||
return false;
|
||||
}
|
||||
output->resize(static_cast<size_t>(expected));
|
||||
env->GetFloatArrayRegion(source, 0, expected, output->data());
|
||||
return !env->ExceptionCheck();
|
||||
}
|
||||
|
||||
bool IsValidNoisePair(float read, float shot) {
|
||||
return std::isfinite(read) && read >= 0.0f &&
|
||||
std::isfinite(shot) && shot >= 0.0f &&
|
||||
(read > 0.0f || shot > 0.0f);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" JNIEXPORT jint JNICALL
|
||||
Java_com_hinnka_mycamera_processor_MgcSpatialStrengthMapGenerator_nativeCompute(
|
||||
JNIEnv* env,
|
||||
jobject,
|
||||
jint layout,
|
||||
jobject fused_fixed16_buffer,
|
||||
jint width,
|
||||
jint height,
|
||||
jint cfa_pattern,
|
||||
jobject alignment_buffer,
|
||||
jint alignment_width,
|
||||
jint alignment_height,
|
||||
jobject rejection_buffer,
|
||||
jint rejection_width,
|
||||
jint rejection_height,
|
||||
jint frame_count,
|
||||
jfloatArray input_read_noise_array,
|
||||
jfloatArray input_shot_noise_array,
|
||||
jfloatArray frame_weights_array,
|
||||
jfloatArray kernel_sigmas_array,
|
||||
jfloat rejected_denoise_multiplier,
|
||||
jshortArray output_strength_array,
|
||||
jfloatArray output_read_noise_array,
|
||||
jfloatArray output_shot_noise_array,
|
||||
jfloatArray output_weights_sum_total_diag_0_array,
|
||||
jfloatArray output_weights_sum_total_diag_1_array) {
|
||||
if (fused_fixed16_buffer == nullptr || alignment_buffer == nullptr ||
|
||||
rejection_buffer == nullptr || output_strength_array == nullptr ||
|
||||
output_read_noise_array == nullptr ||
|
||||
output_shot_noise_array == nullptr ||
|
||||
output_weights_sum_total_diag_0_array == nullptr ||
|
||||
output_weights_sum_total_diag_1_array == nullptr ||
|
||||
width <= 0 || height <= 0 || alignment_width <= 0 ||
|
||||
alignment_height <= 0 || rejection_width <= 0 ||
|
||||
rejection_height <= 0 || frame_count <= 1 ||
|
||||
(layout != 0 && layout != 1)) {
|
||||
return -1;
|
||||
}
|
||||
auto* fused_fixed16 = static_cast<int16_t*>(
|
||||
env->GetDirectBufferAddress(fused_fixed16_buffer));
|
||||
auto* alignment = static_cast<float*>(
|
||||
env->GetDirectBufferAddress(alignment_buffer));
|
||||
auto* rejection = static_cast<uint8_t*>(
|
||||
env->GetDirectBufferAddress(rejection_buffer));
|
||||
if (fused_fixed16 == nullptr || alignment == nullptr ||
|
||||
rejection == nullptr) {
|
||||
return -1;
|
||||
}
|
||||
const int64_t fused_samples = layout == 0
|
||||
? ((static_cast<int64_t>(width) + 15) / 16 * 8) *
|
||||
((static_cast<int64_t>(height) + 15) / 16 * 8) * 4
|
||||
: ((static_cast<int64_t>(width) + 15) / 16 * 16) *
|
||||
((static_cast<int64_t>(height) + 15) / 16 * 16) * 3;
|
||||
const int64_t alignment_values =
|
||||
static_cast<int64_t>(alignment_width) * alignment_height *
|
||||
frame_count * 2;
|
||||
const int64_t rejection_values =
|
||||
static_cast<int64_t>(rejection_width) * rejection_height *
|
||||
frame_count;
|
||||
const int64_t output_values =
|
||||
static_cast<int64_t>(rejection_width) * rejection_height;
|
||||
if (env->GetDirectBufferCapacity(fused_fixed16_buffer) <
|
||||
fused_samples * static_cast<int64_t>(sizeof(int16_t)) ||
|
||||
env->GetDirectBufferCapacity(alignment_buffer) <
|
||||
alignment_values * static_cast<int64_t>(sizeof(float)) ||
|
||||
env->GetDirectBufferCapacity(rejection_buffer) < rejection_values ||
|
||||
env->GetArrayLength(output_strength_array) != output_values ||
|
||||
env->GetArrayLength(output_read_noise_array) != 3 ||
|
||||
env->GetArrayLength(output_shot_noise_array) != 3 ||
|
||||
env->GetArrayLength(output_weights_sum_total_diag_0_array) != 3 ||
|
||||
env->GetArrayLength(output_weights_sum_total_diag_1_array) != 3) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
try {
|
||||
std::vector<float> input_read_noise;
|
||||
std::vector<float> input_shot_noise;
|
||||
std::vector<float> frame_weights;
|
||||
std::vector<float> kernel_sigmas;
|
||||
if (!CopyFloatArray(
|
||||
env,
|
||||
input_read_noise_array,
|
||||
frame_count * 3,
|
||||
&input_read_noise) ||
|
||||
!CopyFloatArray(
|
||||
env,
|
||||
input_shot_noise_array,
|
||||
frame_count * 3,
|
||||
&input_shot_noise) ||
|
||||
!CopyFloatArray(
|
||||
env,
|
||||
frame_weights_array,
|
||||
frame_count,
|
||||
&frame_weights) ||
|
||||
!CopyFloatArray(
|
||||
env,
|
||||
kernel_sigmas_array,
|
||||
frame_count,
|
||||
&kernel_sigmas)) {
|
||||
return -1;
|
||||
}
|
||||
// These are the same calibrated parameters used to merge the image. Replacing
|
||||
// an invalid frame/channel with another model would describe different pixels.
|
||||
for (size_t index = 0; index < input_read_noise.size(); ++index) {
|
||||
if (IsValidNoisePair(input_read_noise[index], input_shot_noise[index])) {
|
||||
continue;
|
||||
}
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR,
|
||||
kTag,
|
||||
"MGC Spatial strength rejected noise input channel=%zu frame=%zu "
|
||||
"read=%.6g shot=%.6g",
|
||||
index / frame_count,
|
||||
index % frame_count,
|
||||
input_read_noise[index],
|
||||
input_shot_noise[index]);
|
||||
return -1;
|
||||
}
|
||||
for (int frame = 0; frame < frame_count; ++frame) {
|
||||
if (std::isfinite(frame_weights[frame]) && frame_weights[frame] > 0.0f &&
|
||||
std::isfinite(kernel_sigmas[frame]) && kernel_sigmas[frame] > 0.0f) {
|
||||
continue;
|
||||
}
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR,
|
||||
kTag,
|
||||
"MGC Spatial strength rejected merge input frame=%d "
|
||||
"frameWeight=%.6g kernelSigma=%.6g",
|
||||
frame,
|
||||
frame_weights[frame],
|
||||
kernel_sigmas[frame]);
|
||||
return -1;
|
||||
}
|
||||
if (!std::isfinite(rejected_denoise_multiplier) ||
|
||||
rejected_denoise_multiplier <= 0.0f) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR,
|
||||
kTag,
|
||||
"MGC Spatial strength rejected denoise multiplier=%.6g",
|
||||
rejected_denoise_multiplier);
|
||||
return -1;
|
||||
}
|
||||
std::vector<uint16_t> output(static_cast<size_t>(output_values));
|
||||
photon::mgc_denoise::SpatialStrengthResult diagnostics;
|
||||
const int result = photon::mgc_denoise::ComputeSpatialStrengthMap(
|
||||
layout == 0
|
||||
? photon::mgc_denoise::SpatialStrengthInputLayout::Bayer
|
||||
: photon::mgc_denoise::SpatialStrengthInputLayout::Rgb,
|
||||
fused_fixed16,
|
||||
width,
|
||||
height,
|
||||
cfa_pattern,
|
||||
alignment,
|
||||
alignment_width,
|
||||
alignment_height,
|
||||
rejection,
|
||||
rejection_width,
|
||||
rejection_height,
|
||||
frame_count,
|
||||
input_read_noise.data(),
|
||||
input_shot_noise.data(),
|
||||
frame_weights.data(),
|
||||
kernel_sigmas.data(),
|
||||
rejected_denoise_multiplier,
|
||||
output.data(),
|
||||
&diagnostics);
|
||||
if (result != 0) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR,
|
||||
kTag,
|
||||
"MGC Spatial strength AOT failed result=%d layout=%d "
|
||||
"image=%dx%d alignment=%dx%dx%d rejection=%dx%dx%d",
|
||||
result,
|
||||
layout,
|
||||
width,
|
||||
height,
|
||||
alignment_width,
|
||||
alignment_height,
|
||||
frame_count,
|
||||
rejection_width,
|
||||
rejection_height,
|
||||
frame_count);
|
||||
return result;
|
||||
}
|
||||
uint16_t minimum = std::numeric_limits<uint16_t>::max();
|
||||
uint16_t maximum = 0;
|
||||
uint64_t sum = 0;
|
||||
for (const uint16_t value : output) {
|
||||
minimum = std::min(minimum, value);
|
||||
maximum = std::max(maximum, value);
|
||||
sum += value;
|
||||
}
|
||||
env->SetShortArrayRegion(
|
||||
output_strength_array,
|
||||
0,
|
||||
static_cast<jsize>(output.size()),
|
||||
reinterpret_cast<const jshort*>(output.data()));
|
||||
if (env->ExceptionCheck()) return -1;
|
||||
// NoiseModel's wrapper at 0x5e959c8 prepends a zero quadratic span:
|
||||
// Halide output .0 remains read and output .1 remains shot.
|
||||
env->SetFloatArrayRegion(
|
||||
output_read_noise_array,
|
||||
0,
|
||||
3,
|
||||
diagnostics.output_noise_model_0);
|
||||
env->SetFloatArrayRegion(
|
||||
output_shot_noise_array,
|
||||
0,
|
||||
3,
|
||||
diagnostics.output_noise_model_1);
|
||||
env->SetFloatArrayRegion(
|
||||
output_weights_sum_total_diag_0_array,
|
||||
0,
|
||||
3,
|
||||
diagnostics.output_weights_sum_total_diag_0);
|
||||
env->SetFloatArrayRegion(
|
||||
output_weights_sum_total_diag_1_array,
|
||||
0,
|
||||
3,
|
||||
diagnostics.output_weights_sum_total_diag_1);
|
||||
if (env->ExceptionCheck()) return -1;
|
||||
__android_log_print(
|
||||
ANDROID_LOG_INFO,
|
||||
kTag,
|
||||
"MGC Spatial strength complete layout=%s size=%dx%d frames=%d "
|
||||
"rejectedMultiplier=%.6g q8=%u..%u/%.3f "
|
||||
"read(output0)=[%.6g,%.6g,%.6g] "
|
||||
"shot(output1)=[%.6g,%.6g,%.6g] diag0=[%.6g,%.6g,%.6g] "
|
||||
"diag1=[%.6g,%.6g,%.6g]",
|
||||
layout == 0 ? "BAYER" : "RGB",
|
||||
rejection_width,
|
||||
rejection_height,
|
||||
frame_count,
|
||||
rejected_denoise_multiplier,
|
||||
minimum,
|
||||
maximum,
|
||||
output.empty()
|
||||
? 0.0
|
||||
: static_cast<double>(sum) /
|
||||
static_cast<double>(output.size()),
|
||||
diagnostics.output_noise_model_0[0],
|
||||
diagnostics.output_noise_model_0[1],
|
||||
diagnostics.output_noise_model_0[2],
|
||||
diagnostics.output_noise_model_1[0],
|
||||
diagnostics.output_noise_model_1[1],
|
||||
diagnostics.output_noise_model_1[2],
|
||||
diagnostics.output_weights_sum_total_diag_0[0],
|
||||
diagnostics.output_weights_sum_total_diag_0[1],
|
||||
diagnostics.output_weights_sum_total_diag_0[2],
|
||||
diagnostics.output_weights_sum_total_diag_1[0],
|
||||
diagnostics.output_weights_sum_total_diag_1[1],
|
||||
diagnostics.output_weights_sum_total_diag_1[2]);
|
||||
return 0;
|
||||
} catch (const std::bad_alloc&) {
|
||||
return -2;
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
#include <algorithm>
|
||||
#include <android/log.h>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <jni.h>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
constexpr const char *kLogTag = "MgcStrengthScaler";
|
||||
|
||||
void LogError(const char *message, int sourceWidth, int sourceHeight,
|
||||
int destinationWidth, int destinationHeight) {
|
||||
__android_log_print(ANDROID_LOG_ERROR, kLogTag, message, sourceWidth,
|
||||
sourceHeight, destinationWidth, destinationHeight);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" JNIEXPORT jboolean JNICALL
|
||||
Java_com_hinnka_mycamera_processor_MgcSpatialStrengthMapScaler_nativeScaleBilinearU16(
|
||||
JNIEnv *env, jobject, jshortArray sourceArray, jint sourceWidth,
|
||||
jint sourceHeight, jshortArray destinationArray, jint destinationWidth,
|
||||
jint destinationHeight) {
|
||||
if (!sourceArray || !destinationArray || sourceWidth <= 0 ||
|
||||
sourceHeight <= 0 || destinationWidth <= 0 || destinationHeight <= 0) {
|
||||
LogError("Invalid geometry src=%dx%d dst=%dx%d", sourceWidth, sourceHeight,
|
||||
destinationWidth, destinationHeight);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
const int64_t sourceCount =
|
||||
static_cast<int64_t>(sourceWidth) * sourceHeight;
|
||||
const int64_t destinationCount =
|
||||
static_cast<int64_t>(destinationWidth) * destinationHeight;
|
||||
if (sourceCount > std::numeric_limits<jsize>::max() ||
|
||||
destinationCount > std::numeric_limits<jsize>::max() ||
|
||||
env->GetArrayLength(sourceArray) != sourceCount ||
|
||||
env->GetArrayLength(destinationArray) != destinationCount) {
|
||||
LogError("Array size mismatch src=%dx%d dst=%dx%d", sourceWidth,
|
||||
sourceHeight, destinationWidth, destinationHeight);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
auto *sourceElements = env->GetShortArrayElements(sourceArray, nullptr);
|
||||
auto *destinationElements =
|
||||
env->GetShortArrayElements(destinationArray, nullptr);
|
||||
if (!sourceElements || !destinationElements) {
|
||||
if (destinationElements) {
|
||||
env->ReleaseShortArrayElements(destinationArray, destinationElements,
|
||||
JNI_ABORT);
|
||||
}
|
||||
if (sourceElements) {
|
||||
env->ReleaseShortArrayElements(sourceArray, sourceElements, JNI_ABORT);
|
||||
}
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
const auto *source = reinterpret_cast<const uint16_t *>(sourceElements);
|
||||
auto *destination = reinterpret_cast<uint16_t *>(destinationElements);
|
||||
bool completed = false;
|
||||
try {
|
||||
std::vector<int> x0(static_cast<size_t>(destinationWidth));
|
||||
std::vector<int> x1(static_cast<size_t>(destinationWidth));
|
||||
std::vector<float> fx(static_cast<size_t>(destinationWidth));
|
||||
for (int x = 0; x < destinationWidth; ++x) {
|
||||
const float sourceX =
|
||||
(static_cast<float>(x) + 0.5f) * sourceWidth / destinationWidth -
|
||||
0.5f;
|
||||
const float sourceFloor = std::floor(sourceX);
|
||||
x0[static_cast<size_t>(x)] =
|
||||
std::clamp(static_cast<int>(sourceFloor), 0, sourceWidth - 1);
|
||||
x1[static_cast<size_t>(x)] =
|
||||
std::min(x0[static_cast<size_t>(x)] + 1, sourceWidth - 1);
|
||||
fx[static_cast<size_t>(x)] =
|
||||
std::clamp(sourceX - sourceFloor, 0.0f, 1.0f);
|
||||
}
|
||||
|
||||
#pragma omp parallel for schedule(static) if (destinationHeight >= 64)
|
||||
for (int y = 0; y < destinationHeight; ++y) {
|
||||
const float sourceY =
|
||||
(static_cast<float>(y) + 0.5f) * sourceHeight / destinationHeight -
|
||||
0.5f;
|
||||
const float sourceFloor = std::floor(sourceY);
|
||||
const int y0 =
|
||||
std::clamp(static_cast<int>(sourceFloor), 0, sourceHeight - 1);
|
||||
const int y1 = std::min(y0 + 1, sourceHeight - 1);
|
||||
const float fy = std::clamp(sourceY - sourceFloor, 0.0f, 1.0f);
|
||||
const auto *topRow = source + static_cast<size_t>(y0) * sourceWidth;
|
||||
const auto *bottomRow = source + static_cast<size_t>(y1) * sourceWidth;
|
||||
auto *destinationRow =
|
||||
destination + static_cast<size_t>(y) * destinationWidth;
|
||||
for (int x = 0; x < destinationWidth; ++x) {
|
||||
const size_t index = static_cast<size_t>(x);
|
||||
const float xWeight = fx[index];
|
||||
const float top = static_cast<float>(topRow[x0[index]]) +
|
||||
xWeight * (static_cast<float>(topRow[x1[index]]) -
|
||||
static_cast<float>(topRow[x0[index]]));
|
||||
const float bottom = static_cast<float>(bottomRow[x0[index]]) +
|
||||
xWeight *
|
||||
(static_cast<float>(bottomRow[x1[index]]) -
|
||||
static_cast<float>(bottomRow[x0[index]]));
|
||||
const float interpolated = top + fy * (bottom - top);
|
||||
destinationRow[x] = static_cast<uint16_t>(std::clamp<long>(
|
||||
std::lrintf(interpolated), 0L, 65535L));
|
||||
}
|
||||
}
|
||||
completed = true;
|
||||
} catch (const std::bad_alloc &) {
|
||||
LogError("Allocation failed src=%dx%d dst=%dx%d", sourceWidth,
|
||||
sourceHeight, destinationWidth, destinationHeight);
|
||||
}
|
||||
|
||||
env->ReleaseShortArrayElements(destinationArray, destinationElements,
|
||||
completed ? 0 : JNI_ABORT);
|
||||
env->ReleaseShortArrayElements(sourceArray, sourceElements, JNI_ABORT);
|
||||
return completed && !env->ExceptionCheck() ? JNI_TRUE : JNI_FALSE;
|
||||
}
|
||||
@@ -68,6 +68,9 @@ import com.hinnka.mycamera.raw.RawSharpeningDefaults
|
||||
import com.hinnka.mycamera.raw.RawAdaptiveExposureMode
|
||||
import com.hinnka.mycamera.raw.RawCaptureProfileCoordinator
|
||||
import com.hinnka.mycamera.raw.RawSceneExposureMath
|
||||
import com.hinnka.mycamera.raw.RawAppliedLensShading
|
||||
import com.hinnka.mycamera.raw.RawAppliedLensShadingMetadata
|
||||
import com.hinnka.mycamera.raw.RawDenoiseHistoryMetadata
|
||||
import com.hinnka.mycamera.raw.RawPhotonHdrMetadata
|
||||
import com.hinnka.mycamera.raw.RawProfileToneMapMode
|
||||
import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
@@ -2343,12 +2346,19 @@ object GalleryManager {
|
||||
) ?: return@withContext
|
||||
preparedDemosaicSourceToRelease = preparedProfile.gpuDemosaicedRawSource
|
||||
updatedMetadata = updatedMetadata.copy(
|
||||
customProperties = RawPhotonHdrMetadata.write(
|
||||
updatedMetadata.customProperties,
|
||||
preparedProfile.hdrRatio,
|
||||
preparedProfile.finalShortGain,
|
||||
preparedProfile.hdrNetPostExposureEv,
|
||||
preparedProfile.hdrNetInputExposureEv,
|
||||
// Single-frame CFA keeps its gain map in the DNG; nothing is pre-applied or denoised.
|
||||
customProperties = RawDenoiseHistoryMetadata.write(
|
||||
RawAppliedLensShadingMetadata.write(
|
||||
RawPhotonHdrMetadata.write(
|
||||
updatedMetadata.customProperties,
|
||||
preparedProfile.hdrRatio,
|
||||
preparedProfile.finalShortGain,
|
||||
preparedProfile.hdrNetPostExposureEv,
|
||||
preparedProfile.hdrNetInputExposureEv,
|
||||
),
|
||||
null,
|
||||
),
|
||||
null,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -3481,9 +3491,7 @@ object GalleryManager {
|
||||
val finalStackResult = rawStackResult ?: return@withContext
|
||||
DngCaptureDiagnostics.put("merge.mergedFrameCount", finalStackResult.mergedFrameCount)
|
||||
DngCaptureDiagnostics.put("merge.outputSize", "${finalStackResult.width}x${finalStackResult.height}")
|
||||
DngCaptureDiagnostics.put("merge.tuningSnr", finalStackResult.mgcDenoiseTuningSnr)
|
||||
DngCaptureDiagnostics.put("merge.readNoise", finalStackResult.mgcDenoiseReadNoise?.contentToString())
|
||||
DngCaptureDiagnostics.put("merge.shotNoise", finalStackResult.mgcDenoiseShotNoise?.contentToString())
|
||||
DngCaptureDiagnostics.put("merge.denoiseHistory", finalStackResult.denoiseHistory?.toString())
|
||||
gpuSourceToRelease = finalStackResult.gpuLinearRgbSource
|
||||
gpuBayerSourceToRelease = finalStackResult.gpuBayerSource
|
||||
fun releaseInitialFusedBuffer() {
|
||||
@@ -3514,11 +3522,7 @@ object GalleryManager {
|
||||
stackWhiteLevel.toFloat()
|
||||
},
|
||||
frameCount = finalStackResult.mergedFrameCount,
|
||||
mgcDenoiseCorrelation = finalStackResult.mgcDenoiseCorrelation,
|
||||
mgcDenoiseReadNoise = finalStackResult.mgcDenoiseReadNoise,
|
||||
mgcDenoiseShotNoise = finalStackResult.mgcDenoiseShotNoise,
|
||||
mgcSpatialStrengthMap = finalStackResult.mgcSpatialStrengthMap,
|
||||
mgcDenoiseTuningSnr = finalStackResult.mgcDenoiseTuningSnr,
|
||||
denoiseHistory = finalStackResult.denoiseHistory,
|
||||
mgcSharpenTuningSnr = finalStackResult.mgcSharpenTuningSnr,
|
||||
mgcSharpenAttenuationScale =
|
||||
finalStackResult.mgcSharpenAttenuationScale,
|
||||
@@ -3540,16 +3544,11 @@ object GalleryManager {
|
||||
else -> MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT
|
||||
}
|
||||
val defaultDenoiseModelAvailable = when (defaultDenoiseMode) {
|
||||
MgcSpatialGpuDenoiseMode.SABRE_DEFAULT ->
|
||||
finalStackResult.mgcDenoiseCorrelation?.size == 128 &&
|
||||
finalStackResult.mgcDenoiseReadNoise?.size == 3 &&
|
||||
finalStackResult.mgcDenoiseShotNoise?.size == 3
|
||||
MgcSpatialGpuDenoiseMode.SABRE_DEFAULT -> finalStackResult.denoiseHistory != null
|
||||
MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT ->
|
||||
MultiFrameConfig.ENABLE_MGC_SPATIAL_DEFAULT_DENOISE &&
|
||||
!finalStackResult.mgcSpatialReferenceOnlyDiagnostic &&
|
||||
finalStackResult.mgcDenoiseCorrelation?.size == 128 &&
|
||||
finalStackResult.mgcDenoiseReadNoise?.size == 3 &&
|
||||
finalStackResult.mgcDenoiseShotNoise?.size == 3
|
||||
finalStackResult.denoiseHistory != null
|
||||
MgcSpatialGpuDenoiseMode.BYPASS_DEFAULT_DENOISE -> true
|
||||
}
|
||||
if (defaultDenoiseRequested && !defaultDenoiseModelAvailable) {
|
||||
@@ -3614,11 +3613,6 @@ object GalleryManager {
|
||||
blackLevel = FloatArray(4),
|
||||
whiteLevel = 65535f,
|
||||
frameCount = 1,
|
||||
mgcDenoiseCorrelation = null,
|
||||
mgcDenoiseReadNoise = null,
|
||||
mgcDenoiseShotNoise = null,
|
||||
mgcSpatialStrengthMap = null,
|
||||
mgcDenoiseTuningSnr = null,
|
||||
)
|
||||
|
||||
val stackedMetadata = metadata
|
||||
@@ -3709,13 +3703,36 @@ object GalleryManager {
|
||||
PLog.e(TAG, "Failed to prepare shared RAW render/DNG profile")
|
||||
return@withContext
|
||||
}
|
||||
// The persisted LinearRaw carries LSC in its pixels while its DNG drops the gain
|
||||
// map; the denoiser needs the applied gains to undo them (docs §3.2).
|
||||
val appliedLensShading = if (defaultDenoised.pixelsIncludeLensShadingCorrection) {
|
||||
RawAppliedLensShading.fromCamera2(
|
||||
rawMetadata.lensShadingMap,
|
||||
rawMetadata.lensShadingMapWidth,
|
||||
rawMetadata.lensShadingMapHeight,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
appliedLensShading?.let {
|
||||
PLog.i(TAG, "Applied LSC persisted ${it.width}x${it.height} hash=${it.hashCode()}")
|
||||
}
|
||||
// Merge ratios and residual ratios of the persisted pixels (docs §2.2, §2.4).
|
||||
val denoiseHistory = defaultDenoised.denoiseHistory
|
||||
PLog.i(TAG, "Denoise history persisted $denoiseHistory")
|
||||
updatedMetadata = updatedMetadata.copy(
|
||||
customProperties = RawPhotonHdrMetadata.write(
|
||||
updatedMetadata.customProperties,
|
||||
dngProfilePreparation.hdrRatio,
|
||||
dngProfilePreparation.finalShortGain,
|
||||
dngProfilePreparation.hdrNetPostExposureEv,
|
||||
dngProfilePreparation.hdrNetInputExposureEv,
|
||||
customProperties = RawDenoiseHistoryMetadata.write(
|
||||
RawAppliedLensShadingMetadata.write(
|
||||
RawPhotonHdrMetadata.write(
|
||||
updatedMetadata.customProperties,
|
||||
dngProfilePreparation.hdrRatio,
|
||||
dngProfilePreparation.finalShortGain,
|
||||
dngProfilePreparation.hdrNetPostExposureEv,
|
||||
dngProfilePreparation.hdrNetInputExposureEv,
|
||||
),
|
||||
appliedLensShading,
|
||||
),
|
||||
denoiseHistory,
|
||||
),
|
||||
)
|
||||
val profileElapsedMs = System.currentTimeMillis() - profileStartMs
|
||||
@@ -3775,6 +3792,8 @@ object GalleryManager {
|
||||
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
|
||||
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
|
||||
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(context, updatedMetadata),
|
||||
appliedLensShading = RawAppliedLensShadingMetadata.read(updatedMetadata.customProperties),
|
||||
denoiseHistory = RawDenoiseHistoryMetadata.read(updatedMetadata.customProperties),
|
||||
rawBlackLevelMode = updatedMetadata.rawBlackLevelMode,
|
||||
rawCustomBlackLevel = updatedMetadata.rawCustomBlackLevel,
|
||||
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
|
||||
@@ -3873,6 +3892,8 @@ object GalleryManager {
|
||||
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
|
||||
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
|
||||
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(context, updatedMetadata),
|
||||
appliedLensShading = appliedLensShading,
|
||||
denoiseHistory = denoiseHistory,
|
||||
rawBlackLevelMode = updatedMetadata.rawBlackLevelMode,
|
||||
rawCustomBlackLevel = updatedMetadata.rawCustomBlackLevel,
|
||||
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
|
||||
@@ -4161,6 +4182,8 @@ object GalleryManager {
|
||||
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
|
||||
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
|
||||
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(context, updatedMetadata),
|
||||
appliedLensShading = RawAppliedLensShadingMetadata.read(updatedMetadata.customProperties),
|
||||
denoiseHistory = RawDenoiseHistoryMetadata.read(updatedMetadata.customProperties),
|
||||
rawBlackLevelMode = updatedMetadata.rawBlackLevelMode,
|
||||
rawCustomBlackLevel = updatedMetadata.rawCustomBlackLevel,
|
||||
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
|
||||
@@ -5624,6 +5647,8 @@ object GalleryManager {
|
||||
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
|
||||
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
|
||||
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(context, updatedMetadata),
|
||||
appliedLensShading = RawAppliedLensShadingMetadata.read(updatedMetadata.customProperties),
|
||||
denoiseHistory = RawDenoiseHistoryMetadata.read(updatedMetadata.customProperties),
|
||||
rawBlackLevelMode = updatedMetadata.rawBlackLevelMode,
|
||||
rawCustomBlackLevel = updatedMetadata.rawCustomBlackLevel,
|
||||
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
|
||||
@@ -5803,6 +5828,8 @@ object GalleryManager {
|
||||
rawBlackPointCorrection = updatedMetadata?.rawBlackPointCorrection ?: 0f,
|
||||
rawWhitePointCorrection = updatedMetadata?.rawWhitePointCorrection ?: 0f,
|
||||
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(context, updatedMetadata),
|
||||
appliedLensShading = RawAppliedLensShadingMetadata.read(rawMetadata.customProperties),
|
||||
denoiseHistory = RawDenoiseHistoryMetadata.read(rawMetadata.customProperties),
|
||||
rawBlackLevelMode = updatedMetadata?.rawBlackLevelMode,
|
||||
rawCustomBlackLevel = updatedMetadata?.rawCustomBlackLevel,
|
||||
rawWhiteLevelMode = updatedMetadata?.rawWhiteLevelMode,
|
||||
|
||||
@@ -31,6 +31,8 @@ import com.hinnka.mycamera.raw.RawDigitalZoomResampling
|
||||
import com.hinnka.mycamera.raw.RawDemosaicProcessor
|
||||
import com.hinnka.mycamera.raw.RawHdrRenderResult
|
||||
import com.hinnka.mycamera.raw.RawMetadata
|
||||
import com.hinnka.mycamera.raw.RawAppliedLensShadingMetadata
|
||||
import com.hinnka.mycamera.raw.RawDenoiseHistoryMetadata
|
||||
import com.hinnka.mycamera.raw.RawPhotonHdrMetadata
|
||||
import com.hinnka.mycamera.raw.RawNoiseProfileManager
|
||||
import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
@@ -586,6 +588,8 @@ class PhotoProcessor(
|
||||
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
|
||||
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
|
||||
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(metadata),
|
||||
appliedLensShading = RawAppliedLensShadingMetadata.read(metadata.customProperties),
|
||||
denoiseHistory = RawDenoiseHistoryMetadata.read(metadata.customProperties),
|
||||
rawBlackLevelMode = metadata.rawBlackLevelMode,
|
||||
rawCustomBlackLevel = metadata.rawCustomBlackLevel,
|
||||
rawWhiteLevelMode = metadata.rawWhiteLevelMode,
|
||||
@@ -674,6 +678,8 @@ class PhotoProcessor(
|
||||
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
|
||||
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
|
||||
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(metadata),
|
||||
appliedLensShading = RawAppliedLensShadingMetadata.read(metadata.customProperties),
|
||||
denoiseHistory = RawDenoiseHistoryMetadata.read(metadata.customProperties),
|
||||
rawBlackLevelMode = metadata.rawBlackLevelMode,
|
||||
rawCustomBlackLevel = metadata.rawCustomBlackLevel,
|
||||
rawWhiteLevelMode = metadata.rawWhiteLevelMode,
|
||||
|
||||
@@ -1,451 +0,0 @@
|
||||
package com.hinnka.mycamera.lut
|
||||
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.Matrix
|
||||
import com.hinnka.mycamera.raw.RawFullscreenQuad
|
||||
import com.hinnka.mycamera.raw.RawGlesProgram
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
|
||||
/**
|
||||
* Shared multi-scale edge-guided chroma denoise shader.
|
||||
*
|
||||
* RAW input is filtered in linear camera RGB opponent space before white
|
||||
* balance and color conversion. Bitmap input retains its luma/chroma transform.
|
||||
* Both paths use a prefiltered luminance guide. RAW luminance is the symmetric
|
||||
* camera-RGB mean; bitmap luminance retains its display-space coefficients.
|
||||
*/
|
||||
object ChromaDenoiseShaders {
|
||||
val PASS_EDGE_GUIDE = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
in vec2 vTexCoord;
|
||||
out vec4 fragColor;
|
||||
uniform sampler2D uInputTexture;
|
||||
uniform vec2 uTexelSize;
|
||||
uniform int uCameraRgbInput;
|
||||
|
||||
float guideSignal(vec3 rgb) {
|
||||
if (uCameraRgbInput != 0) {
|
||||
return (rgb.r + rgb.g + rgb.b) / 3.0;
|
||||
}
|
||||
return dot(rgb, vec3(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
|
||||
float guideAt(vec2 coord) {
|
||||
return guideSignal(texture(uInputTexture, coord).rgb);
|
||||
}
|
||||
|
||||
void main() {
|
||||
float guide = guideAt(vTexCoord) * 0.5;
|
||||
guide += guideAt(vTexCoord + vec2( uTexelSize.x, 0.0)) * 0.125;
|
||||
guide += guideAt(vTexCoord + vec2(-uTexelSize.x, 0.0)) * 0.125;
|
||||
guide += guideAt(vTexCoord + vec2(0.0, uTexelSize.y)) * 0.125;
|
||||
guide += guideAt(vTexCoord + vec2(0.0, -uTexelSize.y)) * 0.125;
|
||||
fragColor = vec4(guide, 0.0, 0.0, 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val PASS_CHROMA_DENOISE = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
in vec2 vTexCoord;
|
||||
out vec4 fragColor;
|
||||
uniform sampler2D uInputTexture;
|
||||
uniform sampler2D uGuideTexture;
|
||||
uniform vec2 uTexelSize;
|
||||
uniform float uH;
|
||||
uniform float uOutputStrength;
|
||||
uniform float uEdgeGuidanceRelaxation;
|
||||
uniform int uCameraRgbInput;
|
||||
// Camera-domain variance models. RB order is
|
||||
// [red slope, red offset, blue slope, blue offset].
|
||||
uniform vec4 uNoiseModelRB;
|
||||
// [green slope, green offset].
|
||||
uniform vec2 uNoiseModelG;
|
||||
|
||||
vec3 rgb2ycbcr(vec3 rgb) {
|
||||
float y = dot(rgb, vec3(0.2126, 0.7152, 0.0722));
|
||||
return vec3(y,
|
||||
dot(rgb, vec3(-0.114572, -0.385428, 0.5 )),
|
||||
dot(rgb, vec3( 0.5, -0.454153, -0.045847)));
|
||||
}
|
||||
vec3 ycbcr2rgb(vec3 yuv) {
|
||||
return vec3(yuv.x + 1.5748 * yuv.z,
|
||||
yuv.x - 0.187324 * yuv.y - 0.468124 * yuv.z,
|
||||
yuv.x + 1.8556 * yuv.y);
|
||||
}
|
||||
|
||||
vec3 channelNoiseVariance(vec3 rgb) {
|
||||
return max(
|
||||
vec3(
|
||||
uNoiseModelRB.x * max(rgb.r, 0.0) + uNoiseModelRB.y,
|
||||
uNoiseModelG.x * max(rgb.g, 0.0) + uNoiseModelG.y,
|
||||
uNoiseModelRB.z * max(rgb.b, 0.0) + uNoiseModelRB.w
|
||||
),
|
||||
vec3(1e-10)
|
||||
);
|
||||
}
|
||||
|
||||
vec3 rgbToFilterSpace(vec3 rgb) {
|
||||
if (uCameraRgbInput != 0) {
|
||||
// Keep every sample in one linear camera-RGB coordinate system.
|
||||
// Exposure invariance is restored after each weighted mean, not
|
||||
// by averaging unstable per-pixel ratios in the shadows.
|
||||
return vec3(
|
||||
(rgb.r + rgb.g + rgb.b) / 3.0,
|
||||
rgb.r - rgb.g,
|
||||
rgb.b - rgb.g
|
||||
);
|
||||
}
|
||||
return rgb2ycbcr(rgb);
|
||||
}
|
||||
|
||||
vec3 filterSpaceToRgb(vec3 value) {
|
||||
if (uCameraRgbInput != 0) {
|
||||
// value.x is the symmetric camera-RGB mean, not green. Recover
|
||||
// the three channels from mean, R-G and B-G without giving any
|
||||
// channel a privileged luminance role.
|
||||
float green = value.x - (value.y + value.z) / 3.0;
|
||||
return max(
|
||||
vec3(
|
||||
green + value.y,
|
||||
green,
|
||||
green + value.z
|
||||
),
|
||||
vec3(0.0)
|
||||
);
|
||||
}
|
||||
return ycbcr2rgb(value);
|
||||
}
|
||||
|
||||
vec2 chromaNoiseSigma(vec3 rgb) {
|
||||
vec3 variance = channelNoiseVariance(rgb);
|
||||
if (uCameraRgbInput != 0) {
|
||||
// Var(R-G) = Var(R) + Var(G), likewise for B-G.
|
||||
return sqrt(max(variance.rb + variance.gg, vec2(1e-10)));
|
||||
}
|
||||
const vec3 cb = vec3(-0.114572, -0.385428, 0.5);
|
||||
const vec3 cr = vec3(0.5, -0.454153, -0.045847);
|
||||
return sqrt(max(
|
||||
vec2(dot(cb * cb, variance), dot(cr * cr, variance)),
|
||||
vec2(1e-10)
|
||||
));
|
||||
}
|
||||
|
||||
float guideNoiseSigma(vec3 rgb) {
|
||||
vec3 variance = channelNoiseVariance(rgb);
|
||||
if (uCameraRgbInput != 0) {
|
||||
return sqrt(max((variance.r + variance.g + variance.b) / 9.0, 1e-10));
|
||||
}
|
||||
const vec3 luma = vec3(0.2126, 0.7152, 0.0722);
|
||||
return sqrt(max(dot(luma * luma, variance), 1e-10));
|
||||
}
|
||||
|
||||
void filterScale(
|
||||
float radius,
|
||||
float centerGuide,
|
||||
float centerSignal,
|
||||
vec2 baseChroma,
|
||||
vec2 chromaGuide,
|
||||
float invGuideH2,
|
||||
vec2 invChromaH2,
|
||||
out vec2 filteredChroma,
|
||||
out float edgeSupport
|
||||
) {
|
||||
// The center estimate anchors each wider scale and prevents a sparse
|
||||
// coarse neighborhood from replacing a small valid color feature.
|
||||
vec2 sumChroma = baseChroma;
|
||||
float sumSignal = centerSignal;
|
||||
float sumWeight = 1.0;
|
||||
float acceptedLumaSupport = 0.0;
|
||||
float totalSupport = 0.0;
|
||||
|
||||
for (int x = -1; x <= 1; x++) {
|
||||
for (int y = -1; y <= 1; y++) {
|
||||
if (x == 0 && y == 0) continue;
|
||||
|
||||
vec2 gridOffset = vec2(float(x), float(y));
|
||||
float distance2 = dot(gridOffset, gridOffset);
|
||||
float spatialWeight = exp(-0.72 * distance2);
|
||||
vec2 offset = gridOffset * uTexelSize * radius;
|
||||
vec2 sampleCoord = vTexCoord + offset;
|
||||
vec3 sampleValue = rgbToFilterSpace(
|
||||
texture(uInputTexture, sampleCoord).rgb
|
||||
);
|
||||
|
||||
float guideDelta =
|
||||
texture(uGuideTexture, sampleCoord).r - centerGuide;
|
||||
float guideWeight =
|
||||
exp(-(guideDelta * guideDelta) * invGuideH2);
|
||||
vec2 chromaDelta = sampleValue.yz - chromaGuide;
|
||||
float chromaDistance =
|
||||
dot(chromaDelta * chromaDelta, invChromaH2);
|
||||
float chromaWeight = exp(-chromaDistance);
|
||||
float weight = spatialWeight * guideWeight * chromaWeight;
|
||||
|
||||
sumChroma += sampleValue.yz * weight;
|
||||
sumSignal += sampleValue.x * weight;
|
||||
sumWeight += weight;
|
||||
acceptedLumaSupport += spatialWeight * guideWeight;
|
||||
totalSupport += spatialWeight;
|
||||
}
|
||||
}
|
||||
|
||||
vec2 averageChroma = sumChroma / max(sumWeight, 1e-6);
|
||||
if (uCameraRgbInput != 0) {
|
||||
// averageChroma is the opponent component of the weighted RGB
|
||||
// mean. Scale that mean back to the center RGB mean so exposure
|
||||
// differences in sparse/coarse samples cannot turn into color.
|
||||
// This ratio-of-means is stable in shadows and exactly preserves
|
||||
// a constant camera chromaticity across an exposure gradient.
|
||||
float averageSignal = sumSignal / max(sumWeight, 1e-6);
|
||||
float signalScale = centerSignal / max(averageSignal, 1e-6);
|
||||
filteredChroma = averageChroma * signalScale;
|
||||
} else {
|
||||
filteredChroma = averageChroma;
|
||||
}
|
||||
// Support reflects the shared luminance guide in both input domains.
|
||||
edgeSupport = acceptedLumaSupport / max(totalSupport, 1e-6);
|
||||
}
|
||||
|
||||
float featheredEdgeSupport(float support, float exponent) {
|
||||
return pow(clamp(support, 0.0, 1.0), exponent);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec4 source = texture(uInputTexture, vTexCoord);
|
||||
if (uH <= 0.00001) {
|
||||
fragColor = source;
|
||||
return;
|
||||
}
|
||||
|
||||
vec3 centerValue = rgbToFilterSpace(source.rgb);
|
||||
vec2 noiseSigma = chromaNoiseSigma(source.rgb);
|
||||
|
||||
float centerGuide = texture(uGuideTexture, vTexCoord).r;
|
||||
float guideSigma = guideNoiseSigma(source.rgb);
|
||||
float guideBandwidthScale =
|
||||
mix(1.0, 4.0, uEdgeGuidanceRelaxation);
|
||||
float guideH =
|
||||
guideSigma * 4.0 * guideBandwidthScale;
|
||||
float invGuideH2 = 1.0 / max(guideH * guideH, 1e-8);
|
||||
// Denoise strength may relax the range threshold slightly, but every
|
||||
// spatial scale shares the same bounded color-edge bandwidth. Large
|
||||
// radii must never gain permission to cross a red/blue boundary.
|
||||
float strengthT = clamp((uH - 1.0) / 7.0, 0.0, 1.0);
|
||||
float chromaEdgeSigmaMultiplier = mix(2.75, 3.5, strengthT);
|
||||
vec2 chromaEdgeH =
|
||||
max(noiseSigma * chromaEdgeSigmaMultiplier, vec2(1e-5));
|
||||
vec2 invChromaEdgeH2 =
|
||||
1.0 / max(chromaEdgeH * chromaEdgeH, vec2(1e-8));
|
||||
|
||||
vec2 fineCandidate;
|
||||
float fineSupport;
|
||||
// Radius one directly covers the one-to-two-pixel sensor grain that
|
||||
// was skipped by the previous sparse fine scale.
|
||||
filterScale(
|
||||
1.0,
|
||||
centerGuide,
|
||||
centerValue.x,
|
||||
centerValue.yz,
|
||||
centerValue.yz,
|
||||
invGuideH2,
|
||||
invChromaEdgeH2,
|
||||
fineCandidate,
|
||||
fineSupport
|
||||
);
|
||||
vec2 fineChroma =
|
||||
mix(centerValue.yz, fineCandidate, uOutputStrength);
|
||||
|
||||
vec2 mediumCandidate;
|
||||
float mediumSupport;
|
||||
filterScale(
|
||||
4.0,
|
||||
centerGuide,
|
||||
centerValue.x,
|
||||
fineChroma,
|
||||
fineChroma,
|
||||
invGuideH2,
|
||||
invChromaEdgeH2,
|
||||
mediumCandidate,
|
||||
mediumSupport
|
||||
);
|
||||
float mediumMix =
|
||||
uOutputStrength * featheredEdgeSupport(mediumSupport, 1.5);
|
||||
vec2 mediumChroma = mix(fineChroma, mediumCandidate, mediumMix);
|
||||
|
||||
vec2 coarseCandidate;
|
||||
float coarseSupport;
|
||||
filterScale(
|
||||
14.0,
|
||||
centerGuide,
|
||||
centerValue.x,
|
||||
mediumChroma,
|
||||
mediumChroma,
|
||||
invGuideH2,
|
||||
invChromaEdgeH2,
|
||||
coarseCandidate,
|
||||
coarseSupport
|
||||
);
|
||||
float coarseMix =
|
||||
uOutputStrength * featheredEdgeSupport(coarseSupport, 2.0);
|
||||
vec2 coarseChroma = mix(mediumChroma, coarseCandidate, coarseMix);
|
||||
|
||||
centerValue.yz = coarseChroma;
|
||||
fragColor = vec4(filterSpaceToRgb(centerValue), source.a);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
|
||||
/** Complete edge-guide + chroma-filter algorithm shared by RAW and bitmap pipelines. */
|
||||
internal class ChromaDenoiseAlgorithm(
|
||||
private val quad: RawFullscreenQuad,
|
||||
) {
|
||||
data class NoiseModel(
|
||||
val redSlope: Float,
|
||||
val redOffset: Float,
|
||||
val greenSlope: Float,
|
||||
val greenOffset: Float,
|
||||
val blueSlope: Float,
|
||||
val blueOffset: Float,
|
||||
)
|
||||
|
||||
data class Input(
|
||||
val sourceTextureId: Int,
|
||||
val guideFramebufferId: Int,
|
||||
val guideTextureId: Int,
|
||||
val outputFramebufferId: Int,
|
||||
val outputTextureId: Int,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val strength: Float,
|
||||
val cameraRgbInput: Boolean,
|
||||
val noiseModel: NoiseModel,
|
||||
)
|
||||
|
||||
data class Output(val textureId: Int, val width: Int, val height: Int)
|
||||
|
||||
private var guideProgram = 0
|
||||
private var filterProgram = 0
|
||||
|
||||
fun initialize(): Boolean {
|
||||
if (guideProgram == 0) {
|
||||
guideProgram = quad.createProgram(
|
||||
ChromaDenoiseShaders.PASS_EDGE_GUIDE,
|
||||
"ChromaDenoiseEdgeGuide",
|
||||
)
|
||||
}
|
||||
if (filterProgram == 0) {
|
||||
filterProgram = quad.createProgram(
|
||||
ChromaDenoiseShaders.PASS_CHROMA_DENOISE,
|
||||
"ChromaDenoiseFilter",
|
||||
)
|
||||
}
|
||||
return guideProgram != 0 && filterProgram != 0
|
||||
}
|
||||
|
||||
fun execute(input: Input): Output? {
|
||||
if (!initialize()) return null
|
||||
require(input.width > 0 && input.height > 0)
|
||||
renderGuide(input)
|
||||
renderFilter(input)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
RawGlesProgram.logErrors("ChromaDenoiseAlgorithm")
|
||||
PLog.d(
|
||||
TAG,
|
||||
"complete: size=${input.width}x${input.height} strength=${input.strength} " +
|
||||
"cameraRgb=${input.cameraRgbInput}",
|
||||
)
|
||||
return Output(input.outputTextureId, input.width, input.height)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (guideProgram != 0) GLES30.glDeleteProgram(guideProgram)
|
||||
if (filterProgram != 0) GLES30.glDeleteProgram(filterProgram)
|
||||
guideProgram = 0
|
||||
filterProgram = 0
|
||||
}
|
||||
|
||||
private fun renderGuide(input: Input) {
|
||||
GLES30.glUseProgram(guideProgram)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, input.guideFramebufferId)
|
||||
GLES30.glViewport(0, 0, input.width, input.height)
|
||||
bindTexture(guideProgram, "uInputTexture", 0, input.sourceTextureId)
|
||||
GLES30.glUniform2f(
|
||||
GLES30.glGetUniformLocation(guideProgram, "uTexelSize"),
|
||||
1f / input.width,
|
||||
1f / input.height,
|
||||
)
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(guideProgram, "uCameraRgbInput"),
|
||||
if (input.cameraRgbInput) 1 else 0,
|
||||
)
|
||||
bindIdentityTextureMatrix(guideProgram)
|
||||
quad.draw(guideProgram)
|
||||
}
|
||||
|
||||
private fun renderFilter(input: Input) {
|
||||
GLES30.glUseProgram(filterProgram)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, input.outputFramebufferId)
|
||||
GLES30.glViewport(0, 0, input.width, input.height)
|
||||
bindTexture(filterProgram, "uInputTexture", 0, input.sourceTextureId)
|
||||
bindTexture(filterProgram, "uGuideTexture", 1, input.guideTextureId)
|
||||
bindIdentityTextureMatrix(filterProgram)
|
||||
GLES30.glUniform2f(
|
||||
GLES30.glGetUniformLocation(filterProgram, "uTexelSize"),
|
||||
1f / input.width,
|
||||
1f / input.height,
|
||||
)
|
||||
GLES30.glUniform1f(
|
||||
GLES30.glGetUniformLocation(filterProgram, "uOutputStrength"),
|
||||
ChromaDenoiseDefaults.outputStrength(input.strength),
|
||||
)
|
||||
GLES30.glUniform1f(
|
||||
GLES30.glGetUniformLocation(filterProgram, "uEdgeGuidanceRelaxation"),
|
||||
ChromaDenoiseDefaults.edgeGuidanceRelaxation(input.strength),
|
||||
)
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(filterProgram, "uCameraRgbInput"),
|
||||
if (input.cameraRgbInput) 1 else 0,
|
||||
)
|
||||
GLES30.glUniform1f(
|
||||
GLES30.glGetUniformLocation(filterProgram, "uH"),
|
||||
ChromaDenoiseDefaults.noiseBandwidth(input.strength),
|
||||
)
|
||||
GLES30.glUniform4f(
|
||||
GLES30.glGetUniformLocation(filterProgram, "uNoiseModelRB"),
|
||||
input.noiseModel.redSlope,
|
||||
input.noiseModel.redOffset,
|
||||
input.noiseModel.blueSlope,
|
||||
input.noiseModel.blueOffset,
|
||||
)
|
||||
GLES30.glUniform2f(
|
||||
GLES30.glGetUniformLocation(filterProgram, "uNoiseModelG"),
|
||||
input.noiseModel.greenSlope,
|
||||
input.noiseModel.greenOffset,
|
||||
)
|
||||
quad.draw(filterProgram)
|
||||
}
|
||||
|
||||
private fun bindTexture(program: Int, uniform: String, unit: Int, textureId: Int) {
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, uniform), unit)
|
||||
}
|
||||
|
||||
private fun bindIdentityTextureMatrix(program: Int) {
|
||||
val identity = FloatArray(16)
|
||||
Matrix.setIdentityM(identity, 0)
|
||||
GLES30.glUniformMatrix4fv(
|
||||
GLES30.glGetUniformLocation(program, "uTexMatrix"),
|
||||
1,
|
||||
false,
|
||||
identity,
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ChromaDenoise"
|
||||
}
|
||||
}
|
||||
@@ -12,11 +12,10 @@ import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import androidx.core.graphics.createBitmap
|
||||
import com.hinnka.mycamera.model.ColorRecipeParams
|
||||
import com.hinnka.mycamera.lut.ChromaDenoiseShaders
|
||||
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
|
||||
import com.hinnka.mycamera.processor.DenoiseStrength
|
||||
import com.hinnka.mycamera.raw.DenoiseProfileNlmConfig
|
||||
import com.hinnka.mycamera.raw.DenoiseProfileShaders
|
||||
import com.hinnka.mycamera.raw.denoise.PhotonMultiScaleDenoiser
|
||||
import com.hinnka.mycamera.raw.denoise.PhotonNoiseModel
|
||||
import com.hinnka.mycamera.utils.LargeDirectBuffer
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlinx.coroutines.asCoroutineDispatcher
|
||||
@@ -84,22 +83,16 @@ class LutImageProcessor(context: Context? = null) {
|
||||
private var texCoordBuffer: FloatBuffer? = null
|
||||
private var indexBuffer: ShortBuffer? = null
|
||||
|
||||
private var bitmapDenoisePreconditionProgram = 0
|
||||
private var bitmapDenoiseNlmInitProgram = 0
|
||||
private var bitmapDenoiseNlmFusedAccuProgram = 0
|
||||
private var bitmapDenoiseNlmFinishProgram = 0
|
||||
private var bitmapSrgbTransferProgram = 0
|
||||
private var bitmapDenoisePassthroughProgram = 0
|
||||
private var computeCapabilitiesChecked = false
|
||||
private var computeCapabilitiesSupported = false
|
||||
private var bitmapChromaDenoiseGuideProgram = 0
|
||||
private var bitmapChromaDenoiseProgram = 0
|
||||
private val bitmapPhotonDenoiser = PhotonMultiScaleDenoiser()
|
||||
private var lutSharpenProgram = 0
|
||||
private var lutLuminanceGainProgram = 0
|
||||
|
||||
private val bitmapDenoiseTexId = IntArray(2)
|
||||
private val bitmapDenoiseFboId = IntArray(2)
|
||||
private var bitmapDenoiseNlmU2BufferId = 0
|
||||
private var bitmapDenoiseNlmBufferPixels = 0
|
||||
private var bitmapDenoiseWidth = 0
|
||||
private var bitmapDenoiseHeight = 0
|
||||
private var lutSharpenTextureId = 0
|
||||
@@ -340,7 +333,6 @@ class LutImageProcessor(context: Context? = null) {
|
||||
val sharpening: Float = colorRecipeParams?.sharpness?.coerceIn(-1f, 1f) ?: 0f
|
||||
val noiseReduction: Float = noiseReductionValue
|
||||
val chromaNoiseReduction: Float = chromaNoiseReductionValue
|
||||
val chromaDenoiseStrength = DenoiseStrength.clamp(chromaNoiseReduction)
|
||||
|
||||
// 激活上下文
|
||||
EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)
|
||||
@@ -353,27 +345,15 @@ class LutImageProcessor(context: Context? = null) {
|
||||
uploadImageTextureFromArgb(argbData, width, height)
|
||||
currentCoroutineContext().ensureActive()
|
||||
|
||||
if (chromaDenoiseStrength > 0) {
|
||||
renderBitmapChromaDenoise(imageTextureId, width, height, chromaDenoiseStrength)
|
||||
currentCoroutineContext().ensureActive()
|
||||
}
|
||||
|
||||
val chromaDenoisedTexId = if (chromaDenoiseStrength > 0) bitmapDenoiseTexId[0] else imageTextureId
|
||||
if (noiseReduction > 0) {
|
||||
renderBitmapDenoiseProfile(chromaDenoisedTexId, width, height, noiseReduction)
|
||||
currentCoroutineContext().ensureActive()
|
||||
}
|
||||
val denoised = renderBitmapPhotonDenoise(imageTextureId, width, height, noiseReduction, chromaNoiseReduction)
|
||||
currentCoroutineContext().ensureActive()
|
||||
|
||||
// 上传 LUT 纹理
|
||||
if (lutConfig != null) {
|
||||
uploadLutTexture(lutConfig)
|
||||
}
|
||||
|
||||
val inputTexId = if (noiseReduction > 0) {
|
||||
bitmapDenoiseTexId[1]
|
||||
} else {
|
||||
chromaDenoisedTexId
|
||||
}
|
||||
val inputTexId = if (denoised) bitmapDenoiseTexId[1] else imageTextureId
|
||||
|
||||
// HDF 光晕效果预处理(在主 shader 之前,需要模糊的光晕纹理)
|
||||
if (halation > 0f) {
|
||||
@@ -486,7 +466,6 @@ class LutImageProcessor(context: Context? = null) {
|
||||
val sharpening: Float = colorRecipeParams?.sharpness?.coerceIn(-1f, 1f) ?: 0f
|
||||
val noiseReduction: Float = noiseReductionValue
|
||||
val chromaNoiseReduction: Float = chromaNoiseReductionValue
|
||||
val chromaDenoiseStrength = DenoiseStrength.clamp(chromaNoiseReduction)
|
||||
|
||||
// 确保上下文激活
|
||||
EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)
|
||||
@@ -502,27 +481,15 @@ class LutImageProcessor(context: Context? = null) {
|
||||
uploadImageTexture(bitmap)
|
||||
currentCoroutineContext().ensureActive()
|
||||
|
||||
if (chromaDenoiseStrength > 0) {
|
||||
renderBitmapChromaDenoise(imageTextureId, width, height, chromaDenoiseStrength)
|
||||
currentCoroutineContext().ensureActive()
|
||||
}
|
||||
|
||||
val chromaDenoisedTexId = if (chromaDenoiseStrength > 0) bitmapDenoiseTexId[0] else imageTextureId
|
||||
if (noiseReduction > 0) {
|
||||
renderBitmapDenoiseProfile(chromaDenoisedTexId, width, height, noiseReduction)
|
||||
currentCoroutineContext().ensureActive()
|
||||
}
|
||||
val denoised = renderBitmapPhotonDenoise(imageTextureId, width, height, noiseReduction, chromaNoiseReduction)
|
||||
currentCoroutineContext().ensureActive()
|
||||
|
||||
// 上传 LUT 纹理
|
||||
if (lutConfig != null) {
|
||||
uploadLutTexture(lutConfig)
|
||||
}
|
||||
|
||||
val inputTexId = if (noiseReduction > 0) {
|
||||
bitmapDenoiseTexId[1]
|
||||
} else {
|
||||
chromaDenoisedTexId
|
||||
}
|
||||
val inputTexId = if (denoised) bitmapDenoiseTexId[1] else imageTextureId
|
||||
val renderColorSpace = bitmap.colorSpace ?: ColorSpace.get(ColorSpace.Named.SRGB)
|
||||
|
||||
// HDF 光晕效果预处理
|
||||
@@ -779,11 +746,11 @@ class LutImageProcessor(context: Context? = null) {
|
||||
setupFramebuffer(width, height)
|
||||
uploadImageTexture(bitmap)
|
||||
|
||||
renderBitmapChromaDenoise(imageTextureId, width, height, strength)
|
||||
val denoised = renderBitmapPhotonDenoise(imageTextureId, width, height, 0f, strength)
|
||||
performRender(
|
||||
width = width,
|
||||
height = height,
|
||||
inputTextureId = bitmapDenoiseTexId[0],
|
||||
inputTextureId = if (denoised) bitmapDenoiseTexId[1] else imageTextureId,
|
||||
inputColorSpace = bitmap.colorSpace ?: ColorSpace.get(ColorSpace.Named.SRGB),
|
||||
lutConfig = null,
|
||||
colorRecipeParams = null,
|
||||
@@ -1304,47 +1271,23 @@ class LutImageProcessor(context: Context? = null) {
|
||||
)
|
||||
}
|
||||
|
||||
private fun ensureBitmapDenoiseProfilePrograms() {
|
||||
/** The Photon denoiser and the sRGB transfer passes around it (docs/photon-multiscale-denoise.md §9). */
|
||||
private fun ensureBitmapPhotonDenoisePrograms(): Boolean {
|
||||
if (!computeCapabilitiesChecked) {
|
||||
computeCapabilitiesSupported = logAndValidateComputeCapabilities()
|
||||
computeCapabilitiesChecked = true
|
||||
}
|
||||
if (!computeCapabilitiesSupported) {
|
||||
ensureBitmapDenoisePassthroughProgram()
|
||||
return
|
||||
}
|
||||
if (bitmapDenoisePreconditionProgram == 0) {
|
||||
bitmapDenoisePreconditionProgram = compileComputeProgram(
|
||||
DenoiseProfileShaders.PRECONDITION_V2,
|
||||
"BitmapDenoise_PreconditionV2",
|
||||
)
|
||||
}
|
||||
if (bitmapDenoiseNlmInitProgram == 0) {
|
||||
bitmapDenoiseNlmInitProgram = compileComputeProgram(
|
||||
DenoiseProfileShaders.INIT,
|
||||
"BitmapDenoise_NLM_Init",
|
||||
)
|
||||
}
|
||||
if (bitmapDenoiseNlmFusedAccuProgram == 0) {
|
||||
bitmapDenoiseNlmFusedAccuProgram = compileComputeProgram(
|
||||
DenoiseProfileShaders.FUSED_ACCU,
|
||||
"BitmapDenoise_NLM_FusedAccu",
|
||||
)
|
||||
}
|
||||
if (bitmapDenoiseNlmFinishProgram == 0) {
|
||||
bitmapDenoiseNlmFinishProgram = compileComputeProgram(
|
||||
DenoiseProfileShaders.FINISH_V2,
|
||||
"BitmapDenoise_NLM_FinishV2",
|
||||
)
|
||||
}
|
||||
if (!computeCapabilitiesSupported) return false
|
||||
ensureBitmapDenoisePassthroughProgram()
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Bitmap denoiseprofile programs initialized: pre=$bitmapDenoisePreconditionProgram " +
|
||||
"init=$bitmapDenoiseNlmInitProgram fusedAccu=$bitmapDenoiseNlmFusedAccuProgram " +
|
||||
"finish=$bitmapDenoiseNlmFinishProgram " +
|
||||
"pass=$bitmapDenoisePassthroughProgram"
|
||||
)
|
||||
if (bitmapSrgbTransferProgram == 0) {
|
||||
bitmapSrgbTransferProgram = createFragmentProgram(
|
||||
IMAGE_VERTEX_SHADER,
|
||||
SRGB_TRANSFER_SHADER,
|
||||
"BitmapDenoise_SrgbTransfer",
|
||||
)
|
||||
}
|
||||
return bitmapSrgbTransferProgram != 0 && bitmapDenoisePassthroughProgram != 0 &&
|
||||
bitmapPhotonDenoiser.initialize()
|
||||
}
|
||||
|
||||
private fun ensureBitmapDenoisePassthroughProgram() {
|
||||
@@ -1357,24 +1300,6 @@ class LutImageProcessor(context: Context? = null) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureBitmapChromaDenoisePrograms() {
|
||||
ensureBitmapDenoisePassthroughProgram()
|
||||
if (bitmapChromaDenoiseGuideProgram == 0) {
|
||||
bitmapChromaDenoiseGuideProgram = createFragmentProgram(
|
||||
IMAGE_VERTEX_SHADER,
|
||||
ChromaDenoiseShaders.PASS_EDGE_GUIDE,
|
||||
"BitmapChromaDenoise_EdgeGuide",
|
||||
)
|
||||
}
|
||||
if (bitmapChromaDenoiseProgram == 0) {
|
||||
bitmapChromaDenoiseProgram = createFragmentProgram(
|
||||
IMAGE_VERTEX_SHADER,
|
||||
ChromaDenoiseShaders.PASS_CHROMA_DENOISE,
|
||||
"BitmapChromaDenoise_MultiScale",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureLutSharpenProgram() {
|
||||
if (lutSharpenProgram == 0) {
|
||||
lutSharpenProgram = createFragmentProgram(
|
||||
@@ -1479,161 +1404,58 @@ class LutImageProcessor(context: Context? = null) {
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
}
|
||||
|
||||
private fun renderBitmapDenoiseProfile(
|
||||
sourceTextureId: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
noiseReduction: Float
|
||||
) {
|
||||
ensureBitmapDenoiseProfilePrograms()
|
||||
setupBitmapDenoiseFramebuffers(width, height)
|
||||
|
||||
val strength = DenoiseStrength.clamp(noiseReduction)
|
||||
if (strength <= 0f || width * height < 2) {
|
||||
renderTexturePassthrough(sourceTextureId, bitmapDenoiseFboId[1], width, height)
|
||||
return
|
||||
}
|
||||
if (!isBitmapDenoiseProfileReady()) {
|
||||
renderTexturePassthrough(sourceTextureId, bitmapDenoiseFboId[1], width, height)
|
||||
return
|
||||
}
|
||||
setupBitmapDenoiseResources(width, height)
|
||||
|
||||
val preconditionTextureId = if (sourceTextureId == bitmapDenoiseTexId[0]) {
|
||||
bitmapDenoiseTexId[1]
|
||||
} else {
|
||||
bitmapDenoiseTexId[0]
|
||||
}
|
||||
val params = buildBitmapDenoiseParams(strength)
|
||||
dispatchBitmapDenoisePreconditionV2(sourceTextureId, preconditionTextureId, width, height, params)
|
||||
dispatchBitmapDenoiseNlm(sourceTextureId, preconditionTextureId, bitmapDenoiseTexId[1], width, height, params)
|
||||
checkGlError("renderBitmapDenoiseProfile")
|
||||
}
|
||||
|
||||
private fun renderBitmapChromaDenoise(
|
||||
/**
|
||||
* §9: sRGB → linear, the Photon denoiser on the nominal Bitmap profile, linear → sRGB.
|
||||
* The result is in bitmapDenoiseTexId[1]; returns false (result not written) when either
|
||||
* strength is zero for both or the compute path is unavailable.
|
||||
*/
|
||||
private fun renderBitmapPhotonDenoise(
|
||||
sourceTextureId: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
noiseReduction: Float,
|
||||
chromaNoiseReduction: Float,
|
||||
targetIndex: Int = 0
|
||||
) {
|
||||
ensureBitmapChromaDenoisePrograms()
|
||||
setupBitmapDenoiseFramebuffers(width, height)
|
||||
|
||||
val strength = DenoiseStrength.clamp(chromaNoiseReduction)
|
||||
val target = targetIndex.coerceIn(0, bitmapDenoiseTexId.lastIndex)
|
||||
val edgeGuidanceRelaxation =
|
||||
ChromaDenoiseDefaults.edgeGuidanceRelaxation(strength)
|
||||
if (strength <= 0f || bitmapChromaDenoiseProgram == 0 ||
|
||||
bitmapChromaDenoiseGuideProgram == 0
|
||||
) {
|
||||
renderTexturePassthrough(sourceTextureId, bitmapDenoiseFboId[target], width, height)
|
||||
return
|
||||
): Boolean {
|
||||
val lumaStrength = DenoiseStrength.clamp(noiseReduction)
|
||||
val chromaStrength = DenoiseStrength.clamp(chromaNoiseReduction)
|
||||
if ((lumaStrength <= 0f && chromaStrength <= 0f) || width * height < 2) return false
|
||||
if (!ensureBitmapPhotonDenoisePrograms()) {
|
||||
PLog.e(TAG, "Bitmap Photon denoise is unavailable: GLES compute support is missing")
|
||||
return false
|
||||
}
|
||||
|
||||
val identityMatrix = FloatArray(16)
|
||||
android.opengl.Matrix.setIdentityM(identityMatrix, 0)
|
||||
val h = ChromaDenoiseDefaults.noiseBandwidth(strength)
|
||||
val guideIndex = if (target == 0) 1 else 0
|
||||
renderBitmapChromaDenoiseEdgeGuide(
|
||||
sourceTextureId,
|
||||
bitmapDenoiseFboId[guideIndex],
|
||||
width,
|
||||
height
|
||||
)
|
||||
val guideTextureId = bitmapDenoiseTexId[guideIndex]
|
||||
|
||||
GLES30.glUseProgram(bitmapChromaDenoiseProgram)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bitmapDenoiseFboId[target])
|
||||
GLES30.glViewport(0, 0, width, height)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uInputTexture"), 0)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, guideTextureId)
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uGuideTexture"),
|
||||
1
|
||||
)
|
||||
GLES30.glUniform2f(
|
||||
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uTexelSize"),
|
||||
1.0f / width,
|
||||
1.0f / height
|
||||
)
|
||||
GLES30.glUniformMatrix4fv(
|
||||
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uMVPMatrix"),
|
||||
1,
|
||||
false,
|
||||
identityMatrix,
|
||||
0
|
||||
)
|
||||
GLES30.glUniform1f(
|
||||
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uOutputStrength"),
|
||||
ChromaDenoiseDefaults.outputStrength(strength)
|
||||
)
|
||||
GLES30.glUniform1f(
|
||||
GLES30.glGetUniformLocation(
|
||||
bitmapChromaDenoiseProgram,
|
||||
"uEdgeGuidanceRelaxation"
|
||||
),
|
||||
edgeGuidanceRelaxation
|
||||
)
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uCameraRgbInput"),
|
||||
0
|
||||
)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uH"), h)
|
||||
GLES30.glUniform4f(
|
||||
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uNoiseModelRB"),
|
||||
BITMAP_DENOISE_A * 2f,
|
||||
BITMAP_DENOISE_B * 2f,
|
||||
BITMAP_DENOISE_A * 2f,
|
||||
BITMAP_DENOISE_B * 2f
|
||||
)
|
||||
GLES30.glUniform2f(
|
||||
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uNoiseModelG"),
|
||||
BITMAP_DENOISE_A * 2f,
|
||||
BITMAP_DENOISE_B * 2f
|
||||
)
|
||||
drawQuad(bitmapChromaDenoiseProgram)
|
||||
checkGlError("renderBitmapChromaDenoise")
|
||||
setupBitmapDenoiseFramebuffers(width, height)
|
||||
renderSrgbTransfer(sourceTextureId, bitmapDenoiseFboId[0], width, height, encode = false)
|
||||
val params = PhotonNoiseModel.buildBitmap(width, height, lumaStrength, chromaStrength)
|
||||
val denoised = checkNotNull(bitmapPhotonDenoiser.denoise(bitmapDenoiseTexId[0], width, height, params)) {
|
||||
"Photon denoise programs are unavailable"
|
||||
}
|
||||
try {
|
||||
renderSrgbTransfer(denoised, bitmapDenoiseFboId[1], width, height, encode = true)
|
||||
} finally {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(denoised), 0)
|
||||
}
|
||||
checkGlError("Bitmap Photon denoise")
|
||||
return true
|
||||
}
|
||||
|
||||
private fun renderBitmapChromaDenoiseEdgeGuide(
|
||||
sourceTextureId: Int,
|
||||
targetFramebufferId: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
) {
|
||||
GLES30.glUseProgram(bitmapChromaDenoiseGuideProgram)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFramebufferId)
|
||||
private fun renderSrgbTransfer(sourceTextureId: Int, targetFboId: Int, width: Int, height: Int, encode: Boolean) {
|
||||
GLES30.glUseProgram(bitmapSrgbTransferProgram)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId)
|
||||
GLES30.glViewport(0, 0, width, height)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId)
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(bitmapChromaDenoiseGuideProgram, "uInputTexture"),
|
||||
0
|
||||
)
|
||||
GLES30.glUniform2f(
|
||||
GLES30.glGetUniformLocation(bitmapChromaDenoiseGuideProgram, "uTexelSize"),
|
||||
1.0f / width,
|
||||
1.0f / height
|
||||
)
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(bitmapChromaDenoiseGuideProgram, "uCameraRgbInput"),
|
||||
0
|
||||
)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(bitmapSrgbTransferProgram, "uInputTexture"), 0)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(bitmapSrgbTransferProgram, "uEncode"), if (encode) 1 else 0)
|
||||
val identityMatrix = FloatArray(16)
|
||||
android.opengl.Matrix.setIdentityM(identityMatrix, 0)
|
||||
GLES30.glUniformMatrix4fv(
|
||||
GLES30.glGetUniformLocation(bitmapChromaDenoiseGuideProgram, "uMVPMatrix"),
|
||||
GLES30.glGetUniformLocation(bitmapSrgbTransferProgram, "uMVPMatrix"),
|
||||
1,
|
||||
false,
|
||||
identityMatrix,
|
||||
0
|
||||
)
|
||||
drawQuad(bitmapChromaDenoiseGuideProgram)
|
||||
checkGlError("renderBitmapChromaDenoiseEdgeGuide")
|
||||
drawQuad(bitmapSrgbTransferProgram)
|
||||
}
|
||||
|
||||
private fun renderTexturePassthrough(sourceTextureId: Int, targetFboId: Int, width: Int, height: Int) {
|
||||
@@ -1781,220 +1603,6 @@ class LutImageProcessor(context: Context? = null) {
|
||||
lutSharpenHeight = 0
|
||||
}
|
||||
|
||||
private data class BitmapDenoiseParams(
|
||||
val strength: Float,
|
||||
val patchRadius: Int,
|
||||
val expectedFineDistance: Float,
|
||||
val expectedGuideDistance: Float,
|
||||
val inverseBandwidth: Float,
|
||||
val coarseGuideWeight: Float,
|
||||
val centralPixelWeight: Float,
|
||||
val p: FloatArray,
|
||||
val signalScale: FloatArray,
|
||||
val aa: FloatArray,
|
||||
val bb: FloatArray,
|
||||
val bias: Float,
|
||||
val scale: Float
|
||||
)
|
||||
|
||||
private fun isBitmapDenoiseProfileReady(): Boolean {
|
||||
return bitmapDenoisePreconditionProgram != 0 &&
|
||||
bitmapDenoiseNlmInitProgram != 0 &&
|
||||
bitmapDenoiseNlmFusedAccuProgram != 0 &&
|
||||
bitmapDenoiseNlmFinishProgram != 0 &&
|
||||
bitmapDenoisePassthroughProgram != 0
|
||||
}
|
||||
|
||||
private fun setupBitmapDenoiseResources(width: Int, height: Int) {
|
||||
val pixelCount = width * height
|
||||
if (
|
||||
bitmapDenoiseNlmBufferPixels == pixelCount &&
|
||||
bitmapDenoiseNlmU2BufferId != 0
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
if (bitmapDenoiseNlmU2BufferId != 0) {
|
||||
GLES31.glDeleteBuffers(1, intArrayOf(bitmapDenoiseNlmU2BufferId), 0)
|
||||
bitmapDenoiseNlmU2BufferId = 0
|
||||
}
|
||||
|
||||
val buffers = IntArray(1)
|
||||
GLES31.glGenBuffers(buffers.size, buffers, 0)
|
||||
bitmapDenoiseNlmU2BufferId = buffers[0]
|
||||
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bitmapDenoiseNlmU2BufferId)
|
||||
GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, pixelCount * 4 * 4, null, GLES31.GL_DYNAMIC_DRAW)
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
|
||||
bitmapDenoiseNlmBufferPixels = pixelCount
|
||||
}
|
||||
|
||||
private fun buildBitmapDenoiseParams(strengthValue: Float): BitmapDenoiseParams {
|
||||
val strength = DenoiseStrength.clamp(strengthValue)
|
||||
val varianceScale = DenoiseStrength.noiseVarianceScale(strength)
|
||||
val a = BITMAP_DENOISE_A * varianceScale
|
||||
val b = BITMAP_DENOISE_B * varianceScale
|
||||
val scale = 1.0f
|
||||
val shadows = max(0.1f - 0.1f * ln(a), 0.7f).coerceAtMost(1.8f)
|
||||
val bias = -max(5f + 0.5f * ln(a), 0.0f)
|
||||
val compensateP = 0.05f / 0.05f.pow(shadows)
|
||||
val patchRadius = DenoiseProfileShaders.PATCH_RADIUS
|
||||
val weightTuning = DenoiseProfileNlmConfig.weightTuning(patchRadius)
|
||||
val centralPixelWeight = 0.1f * scale
|
||||
return BitmapDenoiseParams(
|
||||
strength = DenoiseStrength.outputMix(strength),
|
||||
patchRadius = patchRadius,
|
||||
expectedFineDistance = weightTuning.expectedFineDistance,
|
||||
expectedGuideDistance = weightTuning.expectedGuideDistance,
|
||||
inverseBandwidth = weightTuning.inverseBandwidth,
|
||||
coarseGuideWeight = weightTuning.coarseGuideWeight,
|
||||
centralPixelWeight = centralPixelWeight,
|
||||
p = floatArrayOf(shadows, shadows, shadows, 1.0f),
|
||||
signalScale = floatArrayOf(
|
||||
scale,
|
||||
scale,
|
||||
scale,
|
||||
1.0f
|
||||
),
|
||||
aa = floatArrayOf(a * compensateP, a * compensateP, a * compensateP, 1.0f),
|
||||
bb = floatArrayOf(b, b, b, 1.0f),
|
||||
bias = bias,
|
||||
scale = scale
|
||||
)
|
||||
}
|
||||
|
||||
private fun dispatchBitmapDenoisePreconditionV2(input: Int, output: Int, width: Int, height: Int, params: BitmapDenoiseParams) {
|
||||
GLES31.glUseProgram(bitmapDenoisePreconditionProgram)
|
||||
bindComputeSampler(bitmapDenoisePreconditionProgram, "uInput", 0, input)
|
||||
GLES31.glBindImageTexture(1, output, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
|
||||
setBitmapDenoiseCommonUniforms(bitmapDenoisePreconditionProgram, width, height, params)
|
||||
dispatchBitmapDenoiseImage(width, height, "BitmapDenoise NLM precondition")
|
||||
}
|
||||
|
||||
private fun dispatchBitmapDenoiseNlm(
|
||||
originalTextureId: Int,
|
||||
preconditionedTextureId: Int,
|
||||
outputTextureId: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
params: BitmapDenoiseParams
|
||||
) {
|
||||
dispatchBitmapDenoiseNlmInit(width, height)
|
||||
|
||||
for (offset in DenoiseProfileNlmConfig.searchOffsets) {
|
||||
dispatchBitmapDenoiseNlmFusedAccumulate(
|
||||
preconditionedTextureId,
|
||||
width,
|
||||
height,
|
||||
offset.x,
|
||||
offset.y,
|
||||
params
|
||||
)
|
||||
}
|
||||
|
||||
dispatchBitmapDenoiseNlmFinish(originalTextureId, outputTextureId, width, height, params)
|
||||
}
|
||||
|
||||
private fun dispatchBitmapDenoiseNlmInit(width: Int, height: Int) {
|
||||
GLES31.glUseProgram(bitmapDenoiseNlmInitProgram)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bitmapDenoiseNlmU2BufferId)
|
||||
GLES31.glUniform2i(GLES31.glGetUniformLocation(bitmapDenoiseNlmInitProgram, "uImageSize"), width, height)
|
||||
setBitmapDenoiseStripeUniforms(bitmapDenoiseNlmInitProgram, height)
|
||||
dispatchBitmapDenoiseImage(width, height, "BitmapDenoise NLM init")
|
||||
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
|
||||
}
|
||||
|
||||
private fun dispatchBitmapDenoiseNlmFusedAccumulate(
|
||||
input: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
qx: Int,
|
||||
qy: Int,
|
||||
params: BitmapDenoiseParams
|
||||
) {
|
||||
GLES31.glUseProgram(bitmapDenoiseNlmFusedAccuProgram)
|
||||
bindComputeSampler(bitmapDenoiseNlmFusedAccuProgram, "uInput", 0, input)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bitmapDenoiseNlmU2BufferId)
|
||||
GLES31.glUniform2i(GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uImageSize"), width, height)
|
||||
setBitmapDenoiseStripeUniforms(bitmapDenoiseNlmFusedAccuProgram, height)
|
||||
GLES31.glUniform2i(GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uQ"), qx, qy)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uExpectedFineDistance"),
|
||||
params.expectedFineDistance
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uExpectedGuideDistance"),
|
||||
params.expectedGuideDistance
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uInverseBandwidth"),
|
||||
params.inverseBandwidth
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uCoarseGuideWeight"),
|
||||
params.coarseGuideWeight
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uCentralPixelWeight"),
|
||||
params.centralPixelWeight
|
||||
)
|
||||
dispatchBitmapDenoiseImage(width, height, "BitmapDenoise NLM fused accu q=($qx,$qy)")
|
||||
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
|
||||
}
|
||||
|
||||
private fun dispatchBitmapDenoiseNlmFinish(input: Int, output: Int, width: Int, height: Int, params: BitmapDenoiseParams) {
|
||||
GLES31.glUseProgram(bitmapDenoiseNlmFinishProgram)
|
||||
bindComputeSampler(bitmapDenoiseNlmFinishProgram, "uInput", 0, input)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bitmapDenoiseNlmU2BufferId)
|
||||
GLES31.glBindImageTexture(1, output, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
|
||||
setBitmapDenoiseCommonUniforms(bitmapDenoiseNlmFinishProgram, width, height, params)
|
||||
setBitmapDenoiseStripeUniforms(bitmapDenoiseNlmFinishProgram, height)
|
||||
GLES31.glUniform1f(GLES31.glGetUniformLocation(bitmapDenoiseNlmFinishProgram, "uBias"), params.bias - 0.5f * ln(params.scale))
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(bitmapDenoiseNlmFinishProgram, "uDenoiseMix"),
|
||||
params.strength
|
||||
)
|
||||
dispatchBitmapDenoiseImage(width, height, "BitmapDenoise NLM finish")
|
||||
}
|
||||
|
||||
private fun setBitmapDenoiseStripeUniforms(program: Int, height: Int) {
|
||||
GLES31.glUniform1i(GLES31.glGetUniformLocation(program, "uStripeRowOffset"), 0)
|
||||
GLES31.glUniform1i(GLES31.glGetUniformLocation(program, "uStripeRowCount"), height)
|
||||
}
|
||||
|
||||
private fun setBitmapDenoiseCommonUniforms(program: Int, width: Int, height: Int, params: BitmapDenoiseParams) {
|
||||
GLES31.glUniform2i(GLES31.glGetUniformLocation(program, "uImageSize"), width, height)
|
||||
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uA"), 1, params.aa, 0)
|
||||
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uP"), 1, params.p, 0)
|
||||
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uB"), 1, params.bb, 0)
|
||||
GLES31.glUniform4fv(
|
||||
GLES31.glGetUniformLocation(program, "uSignalScale"),
|
||||
1,
|
||||
params.signalScale,
|
||||
0
|
||||
)
|
||||
}
|
||||
|
||||
private fun bindComputeSampler(program: Int, name: String, unit: Int, textureId: Int) {
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + unit)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, textureId)
|
||||
GLES31.glUniform1i(GLES31.glGetUniformLocation(program, name), unit)
|
||||
}
|
||||
|
||||
private fun dispatchBitmapDenoiseImage(width: Int, height: Int, tag: String) {
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount(width),
|
||||
GlesComputeWorkGroup.imageGroupCount(height),
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
|
||||
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT
|
||||
)
|
||||
checkGlError(tag)
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 HDF 光晕效果 FBO
|
||||
* 使用 1/4 分辨率进行模糊,然后在全分辨率合成
|
||||
@@ -2638,13 +2246,9 @@ class LutImageProcessor(context: Context? = null) {
|
||||
}
|
||||
releaseReadbackBuffer()
|
||||
|
||||
if (bitmapDenoisePreconditionProgram != 0) GLES31.glDeleteProgram(bitmapDenoisePreconditionProgram)
|
||||
if (bitmapDenoiseNlmInitProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseNlmInitProgram)
|
||||
if (bitmapDenoiseNlmFusedAccuProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseNlmFusedAccuProgram)
|
||||
if (bitmapDenoiseNlmFinishProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseNlmFinishProgram)
|
||||
if (bitmapSrgbTransferProgram != 0) GLES30.glDeleteProgram(bitmapSrgbTransferProgram)
|
||||
if (bitmapDenoisePassthroughProgram != 0) GLES30.glDeleteProgram(bitmapDenoisePassthroughProgram)
|
||||
if (bitmapChromaDenoiseGuideProgram != 0) GLES30.glDeleteProgram(bitmapChromaDenoiseGuideProgram)
|
||||
if (bitmapChromaDenoiseProgram != 0) GLES30.glDeleteProgram(bitmapChromaDenoiseProgram)
|
||||
bitmapPhotonDenoiser.release()
|
||||
if (lutSharpenProgram != 0) {
|
||||
GLES30.glDeleteProgram(lutSharpenProgram)
|
||||
lutSharpenProgram = 0
|
||||
@@ -2658,11 +2262,6 @@ class LutImageProcessor(context: Context? = null) {
|
||||
if (bitmapDenoiseFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(bitmapDenoiseFboId[i]), 0)
|
||||
}
|
||||
releaseLutSharpenFramebuffer()
|
||||
if (bitmapDenoiseNlmU2BufferId != 0) {
|
||||
GLES31.glDeleteBuffers(1, intArrayOf(bitmapDenoiseNlmU2BufferId), 0)
|
||||
bitmapDenoiseNlmU2BufferId = 0
|
||||
}
|
||||
bitmapDenoiseNlmBufferPixels = 0
|
||||
|
||||
// 释放 HDF 资源
|
||||
if (hdfExtractBlurHProgram != 0) GLES30.glDeleteProgram(hdfExtractBlurHProgram)
|
||||
@@ -2732,6 +2331,32 @@ class LutImageProcessor(context: Context? = null) {
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
/** sRGB transfer curve, decode (uEncode = 0) or encode, on RGB; alpha passes through. */
|
||||
private val SRGB_TRANSFER_SHADER = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
|
||||
in vec2 vTexCoord;
|
||||
out vec4 fragColor;
|
||||
|
||||
uniform highp sampler2D uInputTexture;
|
||||
uniform int uEncode;
|
||||
|
||||
vec3 decode(vec3 v) {
|
||||
return mix(v / 12.92, pow((v + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), v));
|
||||
}
|
||||
|
||||
vec3 encode(vec3 v) {
|
||||
v = max(v, vec3(0.0));
|
||||
return mix(v * 12.92, 1.055 * pow(v, vec3(1.0 / 2.4)) - 0.055, step(vec3(0.0031308), v));
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec4 c = texture(uInputTexture, vTexCoord);
|
||||
fragColor = vec4(uEncode == 1 ? encode(c.rgb) : decode(max(c.rgb, vec3(0.0))), c.a);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val LUT_LUMINANCE_GAIN_SHADER = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
|
||||
@@ -654,41 +654,6 @@ internal object GlesMgcRawSabreShaders {
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
/**
|
||||
* Reproduces the Q8 `SABRE: Average merge factor` diagnostic at V25 0x34e6964. The original
|
||||
* computes the global mean of `256 / accumulated_green_weight_q8`. This is diagnostic only;
|
||||
* classic Sabre builds its merged NoiseModel from the exposure-normalized frame models.
|
||||
*
|
||||
* Four-by-four reduction keeps the readback small without changing the global average.
|
||||
*/
|
||||
val reciprocalGreenWeight4x4 = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
precision highp sampler2D;
|
||||
precision highp int;
|
||||
uniform sampler2D uAccumulatedWeightsGb;
|
||||
uniform ivec2 uInputSize;
|
||||
layout(location = 0) out vec2 oReciprocalSumAndCount;
|
||||
void main() {
|
||||
ivec2 base = ivec2(gl_FragCoord.xy) * 4;
|
||||
float reciprocalSum = 0.0;
|
||||
float sampleCount = 0.0;
|
||||
for (int y = 0; y < 4; ++y) {
|
||||
for (int x = 0; x < 4; ++x) {
|
||||
ivec2 p = base + ivec2(x, y);
|
||||
if (p.x >= uInputSize.x || p.y >= uInputSize.y) {
|
||||
continue;
|
||||
}
|
||||
float weight = texelFetch(uAccumulatedWeightsGb, p, 0).r;
|
||||
float weightQ8 = max(floor(weight * 256.0 + 0.5), 1.0);
|
||||
reciprocalSum += 256.0 / weightQ8;
|
||||
sampleCount += 1.0;
|
||||
}
|
||||
}
|
||||
oReciprocalSumAndCount = vec2(reciprocalSum, sampleCount);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val dehomogenize = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
|
||||
@@ -2060,45 +2060,6 @@ internal object GlesMgcRawSpatialShaders {
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
/**
|
||||
* Packs the full-resolution normalized Bayer mosaic into MGC Fixed16.
|
||||
*
|
||||
* DownsampleRawF16ToFloatTileSize16 does not consume IEEE FP16. Its F16
|
||||
* input is signed Q14 and has Halide dimensions [quadX, quadY, phase].
|
||||
* The four phase planes are stacked vertically so the readback has the
|
||||
* same conventional planar strides requested by the Halide bounds query:
|
||||
*
|
||||
* address = quadX + quadY * quadWidth
|
||||
* + phase * quadWidth * quadHeight
|
||||
*/
|
||||
val packBayerFixed16 = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
precision highp sampler2D;
|
||||
precision highp int;
|
||||
uniform sampler2D uBayerAndWeight;
|
||||
uniform ivec2 uSourceSize;
|
||||
uniform ivec2 uQuadSize;
|
||||
layout(location = 0) out highp int oBayerFixed16;
|
||||
void main() {
|
||||
ivec2 packed = clamp(
|
||||
ivec2(gl_FragCoord.xy),
|
||||
ivec2(0),
|
||||
ivec2(uQuadSize.x - 1, uQuadSize.y * 4 - 1)
|
||||
);
|
||||
int phase = packed.y / uQuadSize.y;
|
||||
ivec2 quad = ivec2(packed.x, packed.y - phase * uQuadSize.y);
|
||||
ivec2 phaseOffset = ivec2(phase & 1, phase >> 1);
|
||||
ivec2 source = min(quad * 2 + phaseOffset, uSourceSize - ivec2(1));
|
||||
vec2 valueAndWeight = texelFetch(uBayerAndWeight, source, 0).rg;
|
||||
float normalized = max(
|
||||
valueAndWeight.x / max(valueAndWeight.y, 1.0e-8),
|
||||
0.0
|
||||
);
|
||||
oBayerFixed16 = int(round(clamp(normalized * 16384.0, 0.0, 32767.0)));
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
/**
|
||||
* V25 DownsampleRaw16ToGrayHalide (wrapper 0x3c0430c, worker 0x3c0108c):
|
||||
* sum each Bayer quad, apply its asymmetric U16 separable half-add filter, then
|
||||
|
||||
@@ -12,7 +12,8 @@ import android.opengl.GLES31
|
||||
import android.util.Half
|
||||
import com.hinnka.mycamera.camera.MultiFrameConfig
|
||||
import com.hinnka.mycamera.model.SafeImage
|
||||
import com.hinnka.mycamera.raw.MgcSpatialStrengthMap
|
||||
import com.hinnka.mycamera.raw.RawDenoisePipeline
|
||||
import com.hinnka.mycamera.raw.denoise.PhotonMergeNoise
|
||||
import com.hinnka.mycamera.raw.RawFloatTextureTransfer
|
||||
import com.hinnka.mycamera.raw.RawSceneAERawStats
|
||||
import com.hinnka.mycamera.utils.DngCaptureDiagnostics
|
||||
@@ -331,13 +332,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
val totalSubmitMs: Long,
|
||||
)
|
||||
|
||||
private data class QueuedStrengthReadback(
|
||||
val alignment: PreparedTextureReadback,
|
||||
val rejection: PreparedTextureReadback,
|
||||
val fusedFixed16: PreparedTextureReadback,
|
||||
val fusedFixed16PrepareSubmitMs: Long,
|
||||
)
|
||||
|
||||
private data class PreparedTextureReadback(
|
||||
val byteCount: Int,
|
||||
val queuedGpuReadback: QueuedTextureReadback?,
|
||||
@@ -523,7 +517,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
private var sabreMergeProgram = 0
|
||||
private var sabreCopyMaskProgram = 0
|
||||
private var sabreCopyAlphaProgram = 0
|
||||
private var sabreReciprocalGreenWeightProgram = 0
|
||||
private var sabreDehomogenizeProgram = 0
|
||||
private var sabreOutputTransformProgram = 0
|
||||
private var currentMergeCovariance = 0
|
||||
@@ -533,7 +526,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
private var normalizeAotRgbProgram = 0
|
||||
private var copyRgb16ToFloatProgram = 0
|
||||
private var rgbChromaPostprocessor: GlesMgcSpatialRgbChromaPostprocessor? = null
|
||||
private var packBayerFixed16Program = 0
|
||||
private var packRgbFixed16FallbackProgram = 0
|
||||
private var strengthFloatPackProgram = 0
|
||||
private var strengthUnorm8PackProgram = 0
|
||||
@@ -620,7 +612,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
var exportedRgbCompletionTimeline: GpuStackCompletionTimeline? = null
|
||||
var strengthAlignmentHostBuffer: ByteBuffer? = null
|
||||
var strengthRejectionHostBuffer: ByteBuffer? = null
|
||||
var rgbDiagnosticHostBuffer: ByteBuffer? = null
|
||||
var strengthCapture: StrengthCapture? = null
|
||||
var fastMomentsRawStats: RawSceneAERawStats? = null
|
||||
val processStartNs = System.nanoTime()
|
||||
@@ -823,6 +814,18 @@ internal class GlesMgcRawSpatialStacker(
|
||||
exposureScale = 1f,
|
||||
kernelTuning = bayerKernelTuning,
|
||||
)
|
||||
// §2.2 of docs/photon-multiscale-denoise.md: every merged frame enters with its
|
||||
// nominal global weight; the per-pixel rejection maps are not part of the model.
|
||||
val photonMergeNoise = PhotonMergeNoise(
|
||||
RawDenoisePipeline.SPATIAL,
|
||||
referenceCalibration.cameraRgbReadNoise,
|
||||
referenceCalibration.cameraRgbShotNoise,
|
||||
)
|
||||
fun admitMergeNoise(calibration: FrameCalibration) = photonMergeNoise.add(
|
||||
calibration.globalFrameWeight,
|
||||
calibration.cameraRgbReadNoise,
|
||||
calibration.cameraRgbShotNoise,
|
||||
)
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial Bayer kernel referenceSnr=${bayerKernelTuning.referenceSnr} " +
|
||||
@@ -1484,10 +1487,8 @@ internal class GlesMgcRawSpatialStacker(
|
||||
}
|
||||
val spatialNoiseFrameCount =
|
||||
1 + (if (bentoAccepted) 1 else 0) + temporalMergeCount
|
||||
if (outputMode == MgcSpatialOutputMode.RGB ||
|
||||
(MultiFrameConfig.ENABLE_MGC_SPATIAL_DEFAULT_DENOISE &&
|
||||
!referenceOnly && spatialNoiseFrameCount > 1)
|
||||
) {
|
||||
// The RGB AOT merge consumes the captured alignment / rejection atlases.
|
||||
if (outputMode == MgcSpatialOutputMode.RGB) {
|
||||
strengthCapture = createStrengthCapture(
|
||||
frameCount = spatialNoiseFrameCount,
|
||||
referenceCalibration = referenceCalibration,
|
||||
@@ -1538,6 +1539,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
),
|
||||
)
|
||||
}
|
||||
admitMergeNoise(referenceCalibration)
|
||||
strengthCapture?.let { capture ->
|
||||
captureStrengthFrame(
|
||||
capture = capture,
|
||||
@@ -1578,6 +1580,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
),
|
||||
)
|
||||
}
|
||||
admitMergeNoise(checkNotNull(bentoCalibration))
|
||||
strengthCapture?.let { capture ->
|
||||
captureStrengthFrame(
|
||||
capture = capture,
|
||||
@@ -1624,6 +1627,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
),
|
||||
)
|
||||
}
|
||||
admitMergeNoise(referenceCalibration)
|
||||
strengthCapture?.let { capture ->
|
||||
captureStrengthFrame(
|
||||
capture = capture,
|
||||
@@ -1802,6 +1806,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
),
|
||||
)
|
||||
}
|
||||
admitMergeNoise(prepared.calibration)
|
||||
strengthCapture?.let { capture ->
|
||||
captureStrengthFrame(
|
||||
capture = capture,
|
||||
@@ -1838,17 +1843,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
"expected=${capture.frameCount}"
|
||||
}
|
||||
}
|
||||
var strengthQueueElapsedMs = 0L
|
||||
var queuedStrengthReadback = if (
|
||||
readyStrengthCapture?.outputMode == MgcSpatialOutputMode.BAYER
|
||||
) {
|
||||
val startNs = System.nanoTime()
|
||||
queueStrengthReadback(readyStrengthCapture, accumulatorColor).also {
|
||||
strengthQueueElapsedMs = (System.nanoTime() - startNs) / 1_000_000L
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val lensShadingCorrectionApplied: Boolean
|
||||
if (outputMode == MgcSpatialOutputMode.RGB) {
|
||||
check(rgbMergeFrames.size == mergedFrames) {
|
||||
@@ -1895,15 +1889,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
cpuOutput = rgbOutput.cpuBuffer
|
||||
exportedRgbTexture = rgbOutput.gpuTexture
|
||||
exportedRgbCompletionTimeline = rgbOutput.completionTimeline
|
||||
rgbDiagnosticHostBuffer = rgbOutput.diagnosticFixed16?.cpuBuffer
|
||||
val startNs = System.nanoTime()
|
||||
queuedStrengthReadback = queueStrengthReadback(
|
||||
capture = aotCapture,
|
||||
preparedAlignment = preparedStrengthAtlases.first,
|
||||
preparedRejection = preparedStrengthAtlases.second,
|
||||
preparedFusedFixed16 = checkNotNull(rgbOutput.diagnosticFixed16),
|
||||
)
|
||||
strengthQueueElapsedMs = (System.nanoTime() - startNs) / 1_000_000L
|
||||
lensShadingCorrectionApplied = hasLensShading()
|
||||
PLog.i(
|
||||
TAG,
|
||||
@@ -1929,133 +1914,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
}
|
||||
lensShadingCorrectionApplied = false
|
||||
}
|
||||
if (queuedStrengthReadback != null) {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial strength readback queued mode=${outputMode.name} bytes=" +
|
||||
"${queuedStrengthReadback.alignment.byteCount.toLong() +
|
||||
queuedStrengthReadback.rejection.byteCount.toLong() +
|
||||
queuedStrengthReadback.fusedFixed16.byteCount.toLong()} " +
|
||||
"fixed16PrepareSubmit=" +
|
||||
"${queuedStrengthReadback.fusedFixed16PrepareSubmitMs}ms " +
|
||||
"modes=${queuedStrengthReadback.alignment.mode}/" +
|
||||
"${queuedStrengthReadback.rejection.mode}/" +
|
||||
"${queuedStrengthReadback.fusedFixed16.mode} " +
|
||||
"alignmentSubmit=${queuedStrengthReadback.alignment.totalSubmitMs}ms " +
|
||||
"rejectionSubmit=${queuedStrengthReadback.rejection.totalSubmitMs}ms " +
|
||||
"fixed16Submit=${queuedStrengthReadback.fusedFixed16.totalSubmitMs}ms " +
|
||||
"enqueue=${strengthQueueElapsedMs}ms",
|
||||
)
|
||||
}
|
||||
// Bayer queues all three diagnostics before output materialization. RGB packs the
|
||||
// exact merged camera-RGB signal during tiled reconstruction, then queues the two
|
||||
// matching RGB-resolution temporal atlases before resolving the RGB AOT.
|
||||
val strengthResolveStartNs = System.nanoTime()
|
||||
val spatialDenoiseEnabled =
|
||||
MultiFrameConfig.ENABLE_MGC_SPATIAL_DEFAULT_DENOISE && !referenceOnly
|
||||
val spatialNoiseModel = if (spatialDenoiseEnabled) {
|
||||
if (spatialNoiseFrameCount == 1) {
|
||||
createIdentitySpatialNoiseModel(referenceCalibration)
|
||||
} else {
|
||||
val capture = checkNotNull(strengthCapture) {
|
||||
"MGC Spatial multi-frame noise capture is unavailable"
|
||||
}
|
||||
val readback = checkNotNull(queuedStrengthReadback) {
|
||||
"MGC Spatial multi-frame noise readback is unavailable"
|
||||
}
|
||||
checkNotNull(resolveSpatialNoiseModel(capture, readback)) {
|
||||
"MGC Spatial multi-frame AOT noise model failed"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (queuedStrengthReadback != null) {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial strength readback resolved mode=${outputMode.name} " +
|
||||
"took=${(System.nanoTime() - strengthResolveStartNs) / 1_000_000L}ms",
|
||||
)
|
||||
}
|
||||
val denoiseModel = if (spatialNoiseModel != null) {
|
||||
when (outputMode) {
|
||||
MgcSpatialOutputMode.BAYER ->
|
||||
MgcSpatialDenoiseModel.fromBayerDiagnostics(
|
||||
outputWeightsSumTotalDiag0 =
|
||||
spatialNoiseModel.outputWeightsSumTotalDiag0,
|
||||
outputWeightsSumTotalDiag1 =
|
||||
spatialNoiseModel.outputWeightsSumTotalDiag1,
|
||||
)
|
||||
MgcSpatialOutputMode.RGB ->
|
||||
MgcSpatialDenoiseModel.fromRgbDiagnostics(
|
||||
outputWeightsSumTotalDiag0 =
|
||||
spatialNoiseModel.outputWeightsSumTotalDiag0,
|
||||
outputWeightsSumTotalDiag1 =
|
||||
spatialNoiseModel.outputWeightsSumTotalDiag1,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val outputShotNoise = spatialNoiseModel?.outputShotNoise?.let { values ->
|
||||
FloatArray(values.size) { channel ->
|
||||
values[channel] * outputExposure.shotNoiseScale
|
||||
}
|
||||
}
|
||||
val outputReadNoise = spatialNoiseModel?.outputReadNoise?.let { values ->
|
||||
FloatArray(values.size) { channel ->
|
||||
values[channel] * outputExposure.readNoiseVarianceScale
|
||||
}
|
||||
}
|
||||
if (spatialDenoiseEnabled) {
|
||||
checkNotNull(spatialNoiseModel) {
|
||||
"MGC Spatial output noise coefficients were not produced"
|
||||
}
|
||||
checkNotNull(denoiseModel) {
|
||||
"MGC Spatial correlation spectrum was not produced"
|
||||
}
|
||||
}
|
||||
if (spatialNoiseModel != null && denoiseModel != null) {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial denoise model aotMode=${outputMode.name} " +
|
||||
"captureFrames=${strengthCapture?.frameCount} " +
|
||||
"diag0=${spatialNoiseModel.outputWeightsSumTotalDiag0.contentToString()} " +
|
||||
"diag1=${spatialNoiseModel.outputWeightsSumTotalDiag1.contentToString()} " +
|
||||
"savannahRatio=${denoiseModel.diagnosticRatio} " +
|
||||
"savannahTaps=[${denoiseModel.outerTap}," +
|
||||
"${denoiseModel.centerTap},${denoiseModel.outerTap}] " +
|
||||
"read=${outputReadNoise?.contentToString()} " +
|
||||
"shot=${outputShotNoise?.contentToString()} " +
|
||||
"outputExposureScale=${outputExposure.normalizationScale} " +
|
||||
"strength=spatial-aot readback=atlas-pbo-deferred",
|
||||
)
|
||||
}
|
||||
checkGlError("MGC Spatial ${outputMode.name} merge")
|
||||
// MGC's base-SNR * sqrt(planned frame count) value is only a pre-merge planning
|
||||
// estimate. FinishRaw leaves its explicit SNR override unset and evaluates the
|
||||
// propagated Spatial output NoiseModel instead, after alignment/rejection weights
|
||||
// and output-exposure normalization have been folded into read/shot.
|
||||
val propagatedOutputSnr = if (outputReadNoise != null && outputShotNoise != null) {
|
||||
MgcSpatialMergeTuning.outputNoiseModelSnr(
|
||||
signal = bayerKernelTuning.referenceSignal *
|
||||
outputExposure.normalizationScale,
|
||||
greenReadVariance = outputReadNoise.getOrElse(1) { Float.NaN },
|
||||
greenShotNoiseFactor = outputShotNoise.getOrElse(1) { Float.NaN },
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val finishRawDenoiseSnr = if (spatialDenoiseEnabled) {
|
||||
checkNotNull(propagatedOutputSnr) {
|
||||
"MGC Spatial output NoiseModel cannot produce a finite SNR"
|
||||
}
|
||||
} else {
|
||||
MgcSpatialMergeTuning.mergedSnr(
|
||||
bayerKernelTuning.referenceSnr,
|
||||
mergedFrames,
|
||||
)
|
||||
}
|
||||
val resultLabel = when {
|
||||
exportedRgbTexture != 0 -> "${gpuLinearRgbStorage.name}_GPU"
|
||||
exportedBayerTexture != 0 -> "BAYER16_GPU"
|
||||
@@ -2067,12 +1926,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
"MGC Spatial ${outputMode.name} merge complete frames=$mergedFrames " +
|
||||
"output=${outputWidth}x$outputHeight " +
|
||||
"referenceSnr=${bayerKernelTuning.referenceSnr} " +
|
||||
"finishRawDenoiseSnr=$finishRawDenoiseSnr " +
|
||||
"finishRawDenoiseSnrSource=${if (propagatedOutputSnr != null) {
|
||||
"spatial-output-noise-model"
|
||||
} else {
|
||||
"reference-snr-frame-count-fallback"
|
||||
}} " +
|
||||
"lscApplied=$lensShadingCorrectionApplied result=$resultLabel " +
|
||||
"programInit=${programInitMs}ms " +
|
||||
"queueMode=${if (outputMode == MgcSpatialOutputMode.RGB) {
|
||||
@@ -2118,13 +1971,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
},
|
||||
lensShadingCorrectionApplied = lensShadingCorrectionApplied,
|
||||
mergedFrameCount = mergedFrames,
|
||||
mgcDenoiseCorrelation = denoiseModel?.correlation,
|
||||
mgcDenoiseReadNoise = outputReadNoise,
|
||||
mgcDenoiseShotNoise = outputShotNoise,
|
||||
mgcSpatialStrengthMap = spatialNoiseModel?.strengthMap?.let(
|
||||
::mapSpatialStrengthToOutputCoordinates,
|
||||
),
|
||||
mgcDenoiseTuningSnr = finishRawDenoiseSnr,
|
||||
denoiseHistory = photonMergeNoise.history(outputExposure.normalizationScale),
|
||||
mgcSharpenTuningSnr = bayerKernelTuning.referenceSnr,
|
||||
mgcSharpenAttenuationScale = finishRawSharpenAttenuationScale,
|
||||
mgcSpatialReferenceOnlyDiagnostic = referenceOnly,
|
||||
@@ -2141,7 +1988,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
GlesGpuScheduler.restoreCurrentThreadPriority(originalThreadPriority, TAG)
|
||||
LargeDirectBuffer.free(strengthAlignmentHostBuffer)
|
||||
LargeDirectBuffer.free(strengthRejectionHostBuffer)
|
||||
LargeDirectBuffer.free(rgbDiagnosticHostBuffer)
|
||||
if (!returned) {
|
||||
exportedRgbCompletionTimeline?.releasePending()
|
||||
LargeDirectBuffer.free(cpuOutput)
|
||||
@@ -2303,12 +2149,15 @@ internal class GlesMgcRawSpatialStacker(
|
||||
exposureScale = 1f,
|
||||
kernelTuning = kernelTuning,
|
||||
)
|
||||
val noiseFrames = arrayListOf(
|
||||
MgcSabreMergedNoiseModel.Frame(
|
||||
referenceCalibration.cameraRgbReadNoise,
|
||||
referenceCalibration.cameraRgbShotNoise,
|
||||
),
|
||||
)
|
||||
// §2.2 of docs/photon-multiscale-denoise.md: Sabre merges its frames with equal
|
||||
// nominal weight.
|
||||
val photonMergeNoise = PhotonMergeNoise(
|
||||
RawDenoisePipeline.SABRE,
|
||||
referenceCalibration.cameraRgbReadNoise,
|
||||
referenceCalibration.cameraRgbShotNoise,
|
||||
).apply {
|
||||
add(1f, referenceCalibration.cameraRgbReadNoise, referenceCalibration.cameraRgbShotNoise)
|
||||
}
|
||||
val sabreResolveFinalBlackLevel =
|
||||
sabreResolveBlackLevel(referenceCalibration.blackLevels)
|
||||
PLog.i(
|
||||
@@ -2380,10 +2229,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
referenceExposure / validExposureProduct(frame.exposureProduct)
|
||||
).toFloat().coerceIn(MIN_EXPOSURE_SCALE, MAX_EXPOSURE_SCALE)
|
||||
val calibration = calibrationForFrame(frame, exposureScale, kernelTuning)
|
||||
noiseFrames += MgcSabreMergedNoiseModel.Frame(
|
||||
calibration.cameraRgbReadNoise,
|
||||
calibration.cameraRgbShotNoise,
|
||||
)
|
||||
photonMergeNoise.add(1f, calibration.cameraRgbReadNoise, calibration.cameraRgbShotNoise)
|
||||
uploadRaw(images[index], currentRaw, "Sabre frame $index")
|
||||
renderSabreExtract(currentRaw, currentExtracted, extractedWidth, extractedHeight)
|
||||
val noiseTexture = createSabreNoiseLut(referenceCalibration, calibration)
|
||||
@@ -2479,23 +2325,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
GlesGpuScheduler.yieldToUiRenderer()
|
||||
}
|
||||
|
||||
val sabreAverageMergeFactor = readSabreAverageMergeFactor(
|
||||
accumulatedWeightsGb = accumulatedWeightsGb,
|
||||
)
|
||||
val mergedNoiseModel = MgcSabreMergedNoiseModel.merge(
|
||||
noiseFrames,
|
||||
kernelTuning.referenceSnr,
|
||||
PhotonCoreImagingTuning.denoise.noiseSpectrumSeed,
|
||||
)
|
||||
PLog.i(
|
||||
SABRE_TAG,
|
||||
"MGC Sabre merged NoiseModel diagnosticAverageMergeFactor=$sabreAverageMergeFactor " +
|
||||
"snrCorrection=${MgcSabreMergedNoiseModel.snrCorrection(kernelTuning.referenceSnr)} " +
|
||||
"read=${mergedNoiseModel.read.contentToString()} " +
|
||||
"shot=${mergedNoiseModel.shot.contentToString()} " +
|
||||
"spectrumSeed=${mergedNoiseModel.correlation[0]}",
|
||||
)
|
||||
|
||||
renderSabreDehomogenize(
|
||||
accumulatedColor,
|
||||
accumulatedWeightsGb,
|
||||
@@ -2636,19 +2465,11 @@ internal class GlesMgcRawSpatialStacker(
|
||||
}
|
||||
}
|
||||
checkGlError("MGC Sabre Resolve/VGN color noise")
|
||||
// Classic Sabre composes exposure-normalized frame models and applies its SNR
|
||||
// correction before FinishRaw estimates SNR from the resulting green coefficients.
|
||||
val finishRawDenoiseSnr = checkNotNull(MgcSpatialMergeTuning.outputNoiseModelSnr(
|
||||
signal = kernelTuning.referenceSignal,
|
||||
greenReadVariance = mergedNoiseModel.read[1],
|
||||
greenShotNoiseFactor = mergedNoiseModel.shot[1],
|
||||
)) { "MGC Sabre merged NoiseModel cannot produce a finite SNR" }
|
||||
PLog.i(
|
||||
SABRE_TAG,
|
||||
"MGC Sabre complete frames=${frames.size} native=${width}x$height " +
|
||||
"output=${outputWidth}x$outputHeight " +
|
||||
"referenceSnr=${kernelTuning.referenceSnr} " +
|
||||
"finishRawDenoiseSnr=$finishRawDenoiseSnr " +
|
||||
"result=${if (exportedTexture != 0) gpuLinearRgbStorage.name + "_GPU" else "RGB16_CPU"} " +
|
||||
"colorNoiseIir=${chromaResult.chromaSubmissionMs}ms " +
|
||||
"chromaFinal=${chromaResult.finalSubmissionMs}ms " +
|
||||
@@ -2676,10 +2497,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
},
|
||||
lensShadingCorrectionApplied = hasLensShading(),
|
||||
mergedFrameCount = frames.size,
|
||||
mgcDenoiseReadNoise = mergedNoiseModel.read,
|
||||
mgcDenoiseShotNoise = mergedNoiseModel.shot,
|
||||
mgcDenoiseCorrelation = mergedNoiseModel.correlation,
|
||||
mgcDenoiseTuningSnr = finishRawDenoiseSnr,
|
||||
denoiseHistory = photonMergeNoise.history(),
|
||||
mgcSharpenTuningSnr = kernelTuning.referenceSnr,
|
||||
mgcSharpenAttenuationScale = sabreResolveParameters.demosaicSharpness,
|
||||
)
|
||||
@@ -3002,75 +2820,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
}
|
||||
}
|
||||
|
||||
private fun readSabreAverageMergeFactor(
|
||||
accumulatedWeightsGb: Int,
|
||||
): Float {
|
||||
val reducedWidth = ceilDiv(width, 4)
|
||||
val reducedHeight = ceilDiv(height, 4)
|
||||
val reduced = createTexture(
|
||||
reducedWidth,
|
||||
reducedHeight,
|
||||
GLES30.GL_RG16F,
|
||||
GLES30.GL_NEAREST,
|
||||
)
|
||||
try {
|
||||
GLES30.glUseProgram(sabreReciprocalGreenWeightProgram)
|
||||
bindTexture(
|
||||
sabreReciprocalGreenWeightProgram,
|
||||
"uAccumulatedWeightsGb",
|
||||
0,
|
||||
accumulatedWeightsGb,
|
||||
)
|
||||
uniform2i(sabreReciprocalGreenWeightProgram, "uInputSize", width, height)
|
||||
draw(
|
||||
sabreReciprocalGreenWeightProgram,
|
||||
reducedWidth,
|
||||
reducedHeight,
|
||||
intArrayOf(reduced),
|
||||
)
|
||||
|
||||
val valueCount = Math.multiplyExact(
|
||||
Math.multiplyExact(reducedWidth, reducedHeight),
|
||||
2,
|
||||
)
|
||||
val readback = ByteBuffer.allocateDirect(
|
||||
Math.multiplyExact(valueCount, Short.SIZE_BYTES),
|
||||
).order(ByteOrder.nativeOrder())
|
||||
bindRenderTargets(intArrayOf(reduced), "MGC Sabre reciprocal green-weight readback")
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
|
||||
GLES30.glReadPixels(
|
||||
0,
|
||||
0,
|
||||
reducedWidth,
|
||||
reducedHeight,
|
||||
GLES30.GL_RG,
|
||||
GLES30.GL_HALF_FLOAT,
|
||||
readback,
|
||||
)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
checkGlError("read MGC Sabre reciprocal green weights")
|
||||
|
||||
val values = readback.asShortBuffer()
|
||||
var reciprocalSum = 0.0
|
||||
var sampleCount = 0.0
|
||||
for (index in 0 until reducedWidth * reducedHeight) {
|
||||
reciprocalSum += Half.toFloat(values.get(index * 2)).toDouble()
|
||||
sampleCount += Half.toFloat(values.get(index * 2 + 1)).toDouble()
|
||||
}
|
||||
check(
|
||||
reciprocalSum.isFinite() && sampleCount.isFinite() &&
|
||||
reciprocalSum > 0.0 && sampleCount > 0.0
|
||||
) {
|
||||
"MGC Sabre accumulated green weights produced an invalid merge factor: " +
|
||||
"sum=$reciprocalSum count=$sampleCount"
|
||||
}
|
||||
return (reciprocalSum / sampleCount).toFloat()
|
||||
} finally {
|
||||
releaseOwnedTexture(reduced, "Sabre reciprocal green-weight reduction")
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderSabreOutputTransform(
|
||||
resolvedRgbPlanes: IntArray,
|
||||
lensShadingTexture: Int,
|
||||
@@ -3226,10 +2975,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
GlesMgcRawSabreShaders.copyAlpha,
|
||||
"mgc_sabre_copy_alpha",
|
||||
)
|
||||
sabreReciprocalGreenWeightProgram = linkProgram(
|
||||
GlesMgcRawSabreShaders.reciprocalGreenWeight4x4,
|
||||
"mgc_sabre_reciprocal_green_weight_4x4",
|
||||
)
|
||||
sabreDehomogenizeProgram = linkProgram(
|
||||
GlesMgcRawSabreShaders.dehomogenize,
|
||||
"mgc_sabre_dehomogenize",
|
||||
@@ -3436,10 +3181,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
GlesMgcRawSpatialShaders.normalizeBayer,
|
||||
"mgc_spatial_bayer16",
|
||||
)
|
||||
packBayerFixed16Program = linkProgram(
|
||||
GlesMgcRawSpatialShaders.packBayerFixed16,
|
||||
"mgc_spatial_bayer_fixed16",
|
||||
)
|
||||
if (supportsComputeReadback) {
|
||||
runCatching {
|
||||
strengthFloatPackProgram = linkComputeProgram(
|
||||
@@ -5851,137 +5592,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
)
|
||||
}
|
||||
|
||||
private fun createIdentitySpatialNoiseModel(
|
||||
referenceCalibration: FrameCalibration,
|
||||
): MgcSpatialStrengthMapGenerator.Result {
|
||||
val geometry = mgcSpatialDiagnosticGeometry(
|
||||
outputMode = outputMode,
|
||||
imageWidth = width,
|
||||
imageHeight = height,
|
||||
)
|
||||
val noise = spatialNoiseParameters(referenceCalibration)
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial single-frame identity noise model " +
|
||||
"strengthQ8=$SPATIAL_IDENTITY_STRENGTH_Q8 " +
|
||||
"read=${noise.read.contentToString()} shot=${noise.shot.contentToString()}",
|
||||
)
|
||||
return MgcSpatialStrengthMapGenerator.Result(
|
||||
strengthMap = MgcSpatialStrengthMap(
|
||||
width = geometry.rejectionWidth,
|
||||
height = geometry.rejectionHeight,
|
||||
q8 = ShortArray(geometry.rejectionWidth * geometry.rejectionHeight) {
|
||||
SPATIAL_IDENTITY_STRENGTH_Q8.toShort()
|
||||
},
|
||||
),
|
||||
outputReadNoise = noise.read,
|
||||
outputShotNoise = noise.shot,
|
||||
outputWeightsSumTotalDiag0 = FloatArray(3) { SPATIAL_IDENTITY_MULTIPLIER },
|
||||
outputWeightsSumTotalDiag1 = FloatArray(3),
|
||||
)
|
||||
}
|
||||
|
||||
private fun queueStrengthReadback(
|
||||
capture: StrengthCapture,
|
||||
accumulator: Int = 0,
|
||||
preparedAlignment: PreparedTextureReadback? = null,
|
||||
preparedRejection: PreparedTextureReadback? = null,
|
||||
preparedFusedFixed16: PreparedTextureReadback? = null,
|
||||
): QueuedStrengthReadback {
|
||||
check(capture.captured.all { it }) {
|
||||
"MGC Spatial noise capture incomplete: ${capture.captured.contentToString()}"
|
||||
}
|
||||
val allocationStartNs = System.nanoTime()
|
||||
val alignment: PreparedTextureReadback
|
||||
val rejection: PreparedTextureReadback
|
||||
if (capture.outputMode == MgcSpatialOutputMode.RGB) {
|
||||
alignment = checkNotNull(preparedAlignment) {
|
||||
"MGC Spatial RGB alignment diagnostics were not prepared"
|
||||
}
|
||||
rejection = checkNotNull(preparedRejection) {
|
||||
"MGC Spatial RGB rejection diagnostics were not prepared"
|
||||
}
|
||||
} else {
|
||||
check(preparedAlignment == null && preparedRejection == null)
|
||||
alignment = queuePreparedTextureReadback(
|
||||
texture = capture.alignmentAtlas,
|
||||
textureWidth = capture.alignmentLayout.atlasWidth,
|
||||
textureHeight = capture.alignmentLayout.atlasHeight,
|
||||
encoding = StrengthReadbackEncoding.FLOAT32,
|
||||
byteCount = strengthAlignmentReadbackByteCount(capture),
|
||||
label = "MGC Spatial strength alignment atlas",
|
||||
atlasLayout = capture.alignmentLayout,
|
||||
)
|
||||
rejection = queuePreparedTextureReadback(
|
||||
texture = capture.rejectionAtlas,
|
||||
textureWidth = capture.rejectionLayout.atlasWidth,
|
||||
textureHeight = capture.rejectionLayout.atlasHeight,
|
||||
encoding = StrengthReadbackEncoding.UNORM8,
|
||||
byteCount = strengthRejectionReadbackByteCount(capture),
|
||||
label = "MGC Spatial strength rejection atlas",
|
||||
atlasLayout = capture.rejectionLayout,
|
||||
)
|
||||
}
|
||||
val fusedFixed16: PreparedTextureReadback
|
||||
val fusedFixed16PrepareSubmitMs: Long
|
||||
if (capture.outputMode == MgcSpatialOutputMode.BAYER) {
|
||||
check(accumulator != 0 && preparedFusedFixed16 == null)
|
||||
val fusedFixed16Readback = allocatePixelPackBuffer(
|
||||
strengthFixed16ReadbackByteCount(capture),
|
||||
"MGC Spatial Bayer Fixed16 noise source",
|
||||
)
|
||||
val quadWidth = ceilDiv(capture.geometry.imageWidth, 16) * 8
|
||||
val quadHeight = ceilDiv(capture.geometry.imageHeight, 16) * 8
|
||||
val fusedFixed16StartNs = System.nanoTime()
|
||||
val fusedFixed16Texture = renderBayerFixed16Planes(accumulator)
|
||||
fusedFixed16PrepareSubmitMs =
|
||||
(System.nanoTime() - fusedFixed16StartNs) / 1_000_000L
|
||||
val queued = queueTextureReadback(
|
||||
texture = fusedFixed16Texture,
|
||||
textureWidth = quadWidth,
|
||||
textureHeight = quadHeight * 4,
|
||||
encoding = StrengthReadbackEncoding.SINT16,
|
||||
storage = fusedFixed16Readback,
|
||||
label = "MGC Spatial Bayer Fixed16 noise source",
|
||||
)
|
||||
fusedFixed16 = PreparedTextureReadback(
|
||||
byteCount = queued.storage.byteCount,
|
||||
queuedGpuReadback = queued,
|
||||
cpuBuffer = null,
|
||||
mode = queued.mode,
|
||||
targetBindMs = queued.targetBindMs,
|
||||
readSubmitMs = queued.readSubmitMs,
|
||||
totalSubmitMs = queued.totalSubmitMs,
|
||||
)
|
||||
} else {
|
||||
check(accumulator == 0)
|
||||
fusedFixed16 = checkNotNull(preparedFusedFixed16) {
|
||||
"MGC Spatial RGB Fixed16 diagnostic signal was not prepared"
|
||||
}
|
||||
check(
|
||||
fusedFixed16.byteCount == strengthFixed16ReadbackByteCount(capture)
|
||||
) {
|
||||
"MGC Spatial RGB Fixed16 readback size=${fusedFixed16.byteCount}, " +
|
||||
"expected=${strengthFixed16ReadbackByteCount(capture)}"
|
||||
}
|
||||
fusedFixed16PrepareSubmitMs = fusedFixed16.totalSubmitMs
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial strength PBOs prepared mode=${capture.outputMode.name} " +
|
||||
"image=${capture.geometry.imageWidth}x${capture.geometry.imageHeight} bytes=" +
|
||||
"${alignment.byteCount.toLong() + rejection.byteCount +
|
||||
fusedFixed16.byteCount} " +
|
||||
"took=${(System.nanoTime() - allocationStartNs) / 1_000_000L}ms",
|
||||
)
|
||||
return QueuedStrengthReadback(
|
||||
alignment = alignment,
|
||||
rejection = rejection,
|
||||
fusedFixed16 = fusedFixed16,
|
||||
fusedFixed16PrepareSubmitMs = fusedFixed16PrepareSubmitMs,
|
||||
)
|
||||
}
|
||||
|
||||
private fun strengthAlignmentReadbackByteCount(capture: StrengthCapture): Int =
|
||||
(
|
||||
capture.alignmentWidth.toLong() * capture.alignmentHeight *
|
||||
@@ -6376,168 +5986,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
}
|
||||
}
|
||||
|
||||
private fun resolveSpatialNoiseModel(
|
||||
capture: StrengthCapture,
|
||||
queued: QueuedStrengthReadback,
|
||||
): MgcSpatialStrengthMapGenerator.Result? {
|
||||
val totalStartNs = System.nanoTime()
|
||||
var diagnosticsMs = 0L
|
||||
var aotMs = 0L
|
||||
var alignment: ByteBuffer? = null
|
||||
var rejection: ByteBuffer? = null
|
||||
var fusedFixed16: ByteBuffer? = null
|
||||
var alignmentGpuMapped = false
|
||||
var rejectionGpuMapped = false
|
||||
var fusedFixed16GpuMapped = false
|
||||
return try {
|
||||
alignment = queued.alignment.queuedGpuReadback?.let { gpuReadback ->
|
||||
mapPixelPackBuffer(
|
||||
gpuReadback.storage.buffer,
|
||||
gpuReadback.storage.byteCount,
|
||||
"MGC Spatial strength alignment atlas",
|
||||
).also { alignmentGpuMapped = true }
|
||||
} ?: checkNotNull(queued.alignment.cpuBuffer).duplicate()
|
||||
.order(ByteOrder.nativeOrder())
|
||||
.apply {
|
||||
position(0)
|
||||
limit(queued.alignment.byteCount)
|
||||
}
|
||||
rejection = queued.rejection.queuedGpuReadback?.let { gpuReadback ->
|
||||
mapPixelPackBuffer(
|
||||
gpuReadback.storage.buffer,
|
||||
gpuReadback.storage.byteCount,
|
||||
"MGC Spatial strength rejection atlas",
|
||||
).also { rejectionGpuMapped = true }
|
||||
} ?: checkNotNull(queued.rejection.cpuBuffer).duplicate()
|
||||
.order(ByteOrder.nativeOrder())
|
||||
.apply {
|
||||
position(0)
|
||||
limit(queued.rejection.byteCount)
|
||||
}
|
||||
fusedFixed16 = queued.fusedFixed16.queuedGpuReadback?.let { gpuReadback ->
|
||||
mapPixelPackBuffer(
|
||||
gpuReadback.storage.buffer,
|
||||
gpuReadback.storage.byteCount,
|
||||
"MGC Spatial ${capture.outputMode.name} Fixed16 noise source",
|
||||
).also { fusedFixed16GpuMapped = true }
|
||||
} ?: checkNotNull(queued.fusedFixed16.cpuBuffer).duplicate()
|
||||
.order(ByteOrder.nativeOrder())
|
||||
.apply {
|
||||
position(0)
|
||||
limit(queued.fusedFixed16.byteCount)
|
||||
}
|
||||
val mappedAlignment = checkNotNull(alignment)
|
||||
val mappedRejection = checkNotNull(rejection)
|
||||
val mappedFusedFixed16 = checkNotNull(fusedFixed16)
|
||||
if (RawStackRuntimeDebug.mgcSpatialInputDiagnosticsEnabled) {
|
||||
val diagnosticsStartNs = System.nanoTime()
|
||||
logSpatialNoiseInputs(capture, mappedAlignment, mappedRejection)
|
||||
diagnosticsMs = (System.nanoTime() - diagnosticsStartNs) / 1_000_000L
|
||||
}
|
||||
val aotStartNs = System.nanoTime()
|
||||
MgcSpatialStrengthMapGenerator.compute(
|
||||
outputMode = capture.outputMode,
|
||||
fusedFixed16 = mappedFusedFixed16,
|
||||
width = capture.geometry.imageWidth,
|
||||
height = capture.geometry.imageHeight,
|
||||
cfaPattern = cfaPattern,
|
||||
alignment = mappedAlignment,
|
||||
alignmentWidth = capture.alignmentWidth,
|
||||
alignmentHeight = capture.alignmentHeight,
|
||||
rejection = mappedRejection,
|
||||
rejectionWidth = capture.rejectionWidth,
|
||||
rejectionHeight = capture.rejectionHeight,
|
||||
frameCount = capture.frameCount,
|
||||
inputReadNoise = capture.inputReadNoise,
|
||||
inputShotNoise = capture.inputShotNoise,
|
||||
frameWeights = capture.frameWeights,
|
||||
kernelSigmas = capture.kernelSigmas,
|
||||
).also {
|
||||
aotMs = (System.nanoTime() - aotStartNs) / 1_000_000L
|
||||
}
|
||||
} finally {
|
||||
val unmapStartNs = System.nanoTime()
|
||||
if (fusedFixed16GpuMapped) {
|
||||
unmapPixelPackBuffer(
|
||||
checkNotNull(queued.fusedFixed16.queuedGpuReadback).storage.buffer,
|
||||
)
|
||||
}
|
||||
if (rejectionGpuMapped) {
|
||||
unmapPixelPackBuffer(
|
||||
checkNotNull(queued.rejection.queuedGpuReadback).storage.buffer,
|
||||
)
|
||||
}
|
||||
if (alignmentGpuMapped) {
|
||||
unmapPixelPackBuffer(
|
||||
checkNotNull(queued.alignment.queuedGpuReadback).storage.buffer,
|
||||
)
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial strength resolve mode=${capture.outputMode.name} " +
|
||||
"diagnostics=${diagnosticsMs}ms " +
|
||||
"aot=${aotMs}ms " +
|
||||
"unmap=${(System.nanoTime() - unmapStartNs) / 1_000_000L}ms " +
|
||||
"total=${(System.nanoTime() - totalStartNs) / 1_000_000L}ms",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun logSpatialNoiseInputs(
|
||||
capture: StrengthCapture,
|
||||
alignmentStorage: ByteBuffer,
|
||||
rejectionStorage: ByteBuffer,
|
||||
) {
|
||||
val alignmentPlane = capture.alignmentWidth * capture.alignmentHeight
|
||||
val alignment = alignmentStorage.duplicate()
|
||||
.order(ByteOrder.nativeOrder())
|
||||
.asFloatBuffer()
|
||||
val alignmentMeanAbs = FloatArray(capture.frameCount)
|
||||
val alignmentMaxAbs = FloatArray(capture.frameCount)
|
||||
for (frame in 0 until capture.frameCount) {
|
||||
var sum = 0.0
|
||||
var maximum = 0f
|
||||
for (component in 0 until 2) {
|
||||
val base = (component * capture.frameCount + frame) * alignmentPlane
|
||||
for (pixel in 0 until alignmentPlane) {
|
||||
val absolute = kotlin.math.abs(alignment.get(base + pixel))
|
||||
sum += absolute.toDouble()
|
||||
maximum = max(maximum, absolute)
|
||||
}
|
||||
}
|
||||
alignmentMeanAbs[frame] =
|
||||
(sum / (alignmentPlane * 2).toDouble()).toFloat()
|
||||
alignmentMaxAbs[frame] = maximum
|
||||
}
|
||||
|
||||
val rejectionPlane = capture.rejectionWidth * capture.rejectionHeight
|
||||
val rejection = rejectionStorage.duplicate()
|
||||
val acceptedWeightMean = FloatArray(capture.frameCount)
|
||||
for (frame in 0 until capture.frameCount) {
|
||||
var sum = 0L
|
||||
val base = frame * rejectionPlane
|
||||
for (pixel in 0 until rejectionPlane) {
|
||||
sum += rejection.get(base + pixel).toInt() and 0xff
|
||||
}
|
||||
acceptedWeightMean[frame] =
|
||||
sum.toFloat() / (rejectionPlane.toFloat() * 255f)
|
||||
}
|
||||
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial noise inputs mode=${capture.outputMode.name} " +
|
||||
"image=${capture.geometry.imageWidth}x${capture.geometry.imageHeight} " +
|
||||
"frames=${capture.frameCount} " +
|
||||
"alignmentMeanAbs=${alignmentMeanAbs.contentToString()} " +
|
||||
"alignmentMaxAbs=${alignmentMaxAbs.contentToString()} " +
|
||||
"acceptedWeightMean=${acceptedWeightMean.contentToString()} " +
|
||||
"read(channel-major)=${capture.inputReadNoise.contentToString()} " +
|
||||
"shot(channel-major)=${capture.inputShotNoise.contentToString()} " +
|
||||
"frameWeight=${capture.frameWeights.contentToString()} " +
|
||||
"kernelSigma=${capture.kernelSigmas.contentToString()}",
|
||||
)
|
||||
}
|
||||
|
||||
private fun logLinearKernelMask(
|
||||
texture: Int,
|
||||
selectedFrameIndex: Int,
|
||||
@@ -6958,9 +6406,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
val inputGains = FloatArray(frames.size) { index ->
|
||||
frames[index].calibration.inputGain
|
||||
}
|
||||
val aotSampleCount = capture.geometry.fixed16SampleCount
|
||||
.also { require(it in 1..Int.MAX_VALUE.toLong()) }
|
||||
.toInt()
|
||||
val aotByteCount = strengthFixed16ReadbackByteCount(capture)
|
||||
val outputBytes = outputWidth.toLong() * outputHeight * 3L * Short.SIZE_BYTES
|
||||
require(outputBytes in 1..Int.MAX_VALUE.toLong())
|
||||
@@ -7037,22 +6482,8 @@ internal class GlesMgcRawSpatialStacker(
|
||||
"hasShort=${ultrashortWeight != 0} stage=before-rgb16")
|
||||
chromaPostprocessor.markTileWritten(fullOutputTile)
|
||||
|
||||
// The GL upload no longer reads client memory after glTexSubImage2D returns. Reuse the
|
||||
// same native allocation for the planar signed-Q14 diagnostic expected by the lifted
|
||||
// Spatial-noise AOT instead of holding a second full-resolution planar allocation.
|
||||
MgcSpatialRgbMerger.convertPlanarF16ToFixed16(
|
||||
buffer = checkNotNull(aotPlanar),
|
||||
sampleCount = aotSampleCount,
|
||||
)
|
||||
diagnosticFixed16 = PreparedTextureReadback(
|
||||
byteCount = aotByteCount,
|
||||
queuedGpuReadback = null,
|
||||
cpuBuffer = checkNotNull(aotPlanar),
|
||||
mode = "mgc-v25-aot-planar-q14-host",
|
||||
targetBindMs = 0L,
|
||||
readSubmitMs = 0L,
|
||||
totalSubmitMs = aotMs,
|
||||
)
|
||||
// The GL upload no longer reads client memory after glTexSubImage2D returns.
|
||||
LargeDirectBuffer.free(aotPlanar)
|
||||
aotPlanar = null
|
||||
|
||||
releaseRgbFusionPhaseTextures(
|
||||
@@ -8511,31 +7942,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
lensShadingHeight > 0 &&
|
||||
lensShading.size >= lensShadingWidth * lensShadingHeight * 4
|
||||
|
||||
private fun mapSpatialStrengthToOutputCoordinates(
|
||||
source: MgcSpatialStrengthMap,
|
||||
): MgcSpatialStrengthMap {
|
||||
val coveredSource = source.withIdentityBorder(width, height)
|
||||
val targetWidth = ceilDiv(outputWidth, 4)
|
||||
val targetHeight = ceilDiv(outputHeight, 4)
|
||||
if (coveredSource.width == targetWidth && coveredSource.height == targetHeight) {
|
||||
return coveredSource
|
||||
}
|
||||
val startNs = System.nanoTime()
|
||||
val mapped = MgcSpatialStrengthMapScaler.scaleBilinear(
|
||||
source = coveredSource,
|
||||
targetWidth = targetWidth,
|
||||
targetHeight = targetHeight,
|
||||
)
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial strength coordinates mapped ${coveredSource.width}x${coveredSource.height} -> " +
|
||||
"${targetWidth}x$targetHeight for native-grid RGB output " +
|
||||
"backend=native-openmp took=" +
|
||||
"${(System.nanoTime() - startNs) / 1_000_000L}ms",
|
||||
)
|
||||
return mapped
|
||||
}
|
||||
|
||||
private fun createNoiseLut(
|
||||
reference: FrameCalibration,
|
||||
current: FrameCalibration,
|
||||
@@ -8640,41 +8046,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
return bayer16
|
||||
}
|
||||
|
||||
private fun renderBayerFixed16Planes(accumulator: Int): Int {
|
||||
// The lifted AOT consumes complete 8x8 Bayer-quad tiles (16x16 sensor
|
||||
// pixels), including a clamped edge tile when the RAW size is odd.
|
||||
val quadWidth = ceilDiv(width, 16) * 8
|
||||
val quadHeight = ceilDiv(height, 16) * 8
|
||||
val packedHeight = quadHeight * 4
|
||||
val bayerFixed16 = createTexture(
|
||||
quadWidth,
|
||||
packedHeight,
|
||||
GLES30.GL_R16I,
|
||||
GLES30.GL_NEAREST,
|
||||
)
|
||||
GLES30.glUseProgram(packBayerFixed16Program)
|
||||
bindTexture(packBayerFixed16Program, "uBayerAndWeight", 0, accumulator)
|
||||
uniform2i(
|
||||
packBayerFixed16Program,
|
||||
"uSourceSize",
|
||||
width,
|
||||
height,
|
||||
)
|
||||
uniform2i(
|
||||
packBayerFixed16Program,
|
||||
"uQuadSize",
|
||||
quadWidth,
|
||||
quadHeight,
|
||||
)
|
||||
draw(
|
||||
packBayerFixed16Program,
|
||||
quadWidth,
|
||||
packedHeight,
|
||||
intArrayOf(bayerFixed16),
|
||||
)
|
||||
return bayerFixed16
|
||||
}
|
||||
|
||||
private fun readBayer16(bayer16: Int): ByteBuffer {
|
||||
val outputBytes = width.toLong() * height.toLong() * 2L
|
||||
val allocationStartNs = System.nanoTime()
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
/** Classic V25 Sabre MergeRaw: 0x344964c -> 0x5f366b4 -> 0x38c8fe0. */
|
||||
internal object MgcSabreMergedNoiseModel {
|
||||
/** Coefficients are in normalized, un-white-balanced camera RGB at reference exposure. */
|
||||
data class Frame(val read: FloatArray, val shot: FloatArray)
|
||||
|
||||
data class Output(val read: FloatArray, val shot: FloatArray, val correlation: FloatArray)
|
||||
|
||||
fun merge(frames: List<Frame>, referenceSnr: Float, noiseSpectrumSeed: Float): Output {
|
||||
require(frames.isNotEmpty())
|
||||
require(noiseSpectrumSeed.isFinite() && noiseSpectrumSeed >= 0f)
|
||||
val readSum = DoubleArray(3)
|
||||
val shotSum = DoubleArray(3)
|
||||
var weightSum = 0.0
|
||||
val alternateWeight = 1f / frames.size.toFloat()
|
||||
for ((index, frame) in frames.withIndex()) {
|
||||
require(frame.read.size == 3 && frame.shot.size == 3)
|
||||
require(frame.read.all { it.isFinite() && it >= 0f })
|
||||
require(frame.shot.all { it.isFinite() && it >= 0f })
|
||||
// V25 assigns the residual to the reference, including float rounding.
|
||||
val weight = if (index == 0) {
|
||||
1f - alternateWeight * (frames.size - 1).toFloat()
|
||||
} else alternateWeight
|
||||
val squaredWeight = (weight * weight).toDouble()
|
||||
weightSum += weight.toDouble()
|
||||
for (channel in 0..2) {
|
||||
readSum[channel] += frame.read[channel].toDouble() * squaredWeight
|
||||
shotSum[channel] += frame.shot[channel].toDouble() * squaredWeight
|
||||
}
|
||||
}
|
||||
// The original accumulates in double and normalizes shot by the weighted signal gain.
|
||||
// All frame models were transported to reference exposure, so their signal gains are 1.
|
||||
val samples = 1f / snrCorrection(referenceSnr)
|
||||
val correction = 1f / samples
|
||||
val read = FloatArray(3) { readSum[it].toFloat() * correction }
|
||||
val shot = FloatArray(3) { (shotSum[it] / weightSum).toFloat() * correction }
|
||||
// This model has no measured input spectrum. AGC's lib_luma_noise_key sets the
|
||||
// constructor seed; neither RBF weight statistics nor frame count scales it.
|
||||
return Output(read, shot, FloatArray(128) { noiseSpectrumSeed })
|
||||
}
|
||||
|
||||
/** Average(1 / d) scales every coefficient by d; it preserves the correlation spectrum. */
|
||||
internal fun snrCorrection(referenceSnr: Float): Float {
|
||||
require(referenceSnr.isFinite() && referenceSnr >= 0f)
|
||||
return when {
|
||||
referenceSnr <= 0.5f -> 0.8f
|
||||
referenceSnr < 4f -> interpolate(referenceSnr, 0.5f, 4f, 0.8f, 1f)
|
||||
referenceSnr < 10f -> interpolate(referenceSnr, 4f, 10f, 1f, 0.7f)
|
||||
else -> 0.7f
|
||||
}
|
||||
}
|
||||
|
||||
private fun interpolate(x: Float, x0: Float, x1: Float, y0: Float, y1: Float): Float {
|
||||
val fraction = (x - x0) / (x1 - x0)
|
||||
return y1 * fraction + y0 * (1f - fraction)
|
||||
}
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.max
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* Recovered MGC Spatial correlation specialization.
|
||||
*
|
||||
* MGC does not infer correlation from the quantized R8 merge masks. At
|
||||
* 0x3632688..0x36327dc it uses the green entries of the two layout-specific
|
||||
* Compute{Bayer,Rgb}NoiseModel diagnostics to fit a symmetric Savannah
|
||||
* three-tap filter [outer, center, outer]. The filter is converted to a
|
||||
* half-bin-centered 128-bin power spectrum by 0x5e9ca0c/0x5e9ce94 and then
|
||||
* normalized to unit mean at 0x3632e8c..0x3632eb4.
|
||||
*/
|
||||
internal object MgcSpatialDenoiseModel {
|
||||
private const val SPECTRUM_SIZE = 128
|
||||
private const val GREEN_CHANNEL = 1
|
||||
private const val MIN_DIAGNOSTIC_TOTAL = 1e-6f
|
||||
private const val IDENTITY_RATIO_THRESHOLD = 1e-4f
|
||||
private const val TWO_PI = 2.0 * Math.PI
|
||||
|
||||
data class Result(
|
||||
val correlation: FloatArray,
|
||||
val diagnosticRatio: Float,
|
||||
val outerTap: Float,
|
||||
val centerTap: Float,
|
||||
)
|
||||
|
||||
fun fromBayerDiagnostics(
|
||||
outputWeightsSumTotalDiag0: FloatArray,
|
||||
outputWeightsSumTotalDiag1: FloatArray,
|
||||
): Result? = fromGreenDiagnostics(
|
||||
outputWeightsSumTotalDiag0,
|
||||
outputWeightsSumTotalDiag1,
|
||||
)
|
||||
|
||||
fun fromRgbDiagnostics(
|
||||
outputWeightsSumTotalDiag0: FloatArray,
|
||||
outputWeightsSumTotalDiag1: FloatArray,
|
||||
): Result? = fromGreenDiagnostics(
|
||||
outputWeightsSumTotalDiag0,
|
||||
outputWeightsSumTotalDiag1,
|
||||
)
|
||||
|
||||
private fun fromGreenDiagnostics(
|
||||
outputWeightsSumTotalDiag0: FloatArray,
|
||||
outputWeightsSumTotalDiag1: FloatArray,
|
||||
): Result? {
|
||||
if (outputWeightsSumTotalDiag0.size != 3 ||
|
||||
outputWeightsSumTotalDiag1.size != 3 ||
|
||||
outputWeightsSumTotalDiag0.any { !it.isFinite() || it < 0f } ||
|
||||
outputWeightsSumTotalDiag1.any { !it.isFinite() || it < 0f }
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
val total = max(
|
||||
outputWeightsSumTotalDiag0[GREEN_CHANNEL],
|
||||
MIN_DIAGNOSTIC_TOTAL,
|
||||
)
|
||||
val ratio =
|
||||
outputWeightsSumTotalDiag1[GREEN_CHANNEL] / (4f * total)
|
||||
if (!ratio.isFinite() || ratio < 0f) return null
|
||||
|
||||
val outerTap: Float
|
||||
val centerTap: Float
|
||||
if (ratio < IDENTITY_RATIO_THRESHOLD) {
|
||||
outerTap = 0f
|
||||
centerTap = 1f
|
||||
} else {
|
||||
val threeRatioMinusOne = 3f * ratio - 1f
|
||||
val oneMinusFourRatio = 1f - 4f * ratio
|
||||
val root = sqrtf(8f * ratio * threeRatioMinusOne + 1f)
|
||||
// MGC's arm64 body at 0x3632750..0x3632754 evaluates
|
||||
// sqrt(root - (1 - 4r)) directly. Immediately above the 1e-4 branch threshold,
|
||||
// both terms round to the same Float and the subtraction collapses to zero.
|
||||
// Rationalizing the exact same expression avoids that cancellation:
|
||||
// root - (1 - 4r) = 8r^2 / (root + 1 - 4r).
|
||||
val filterScale = sqrtf(
|
||||
8f * ratio * ratio / (root + oneMinusFourRatio),
|
||||
)
|
||||
val numerator =
|
||||
1f - 8f * ratio + 20f * ratio * ratio +
|
||||
oneMinusFourRatio * root
|
||||
val denominator =
|
||||
16f * ratio * threeRatioMinusOne + 2f
|
||||
val inverseRootSum = 1f / (oneMinusFourRatio + root)
|
||||
val numeratorQuarterPower = powf(numerator, 0.25f)
|
||||
|
||||
outerTap =
|
||||
0.5f * filterScale *
|
||||
powf(numerator / denominator, 0.25f)
|
||||
centerTap =
|
||||
filterScale *
|
||||
(0.5f / (ratio * powf(denominator, 0.25f))) *
|
||||
inverseRootSum *
|
||||
numerator *
|
||||
numeratorQuarterPower
|
||||
}
|
||||
if (!outerTap.isFinite() || !centerTap.isFinite()) return null
|
||||
|
||||
val correlation = FloatArray(SPECTRUM_SIZE)
|
||||
var energy = 0.0
|
||||
for (index in correlation.indices) {
|
||||
val response =
|
||||
centerTap +
|
||||
2f * outerTap *
|
||||
cos(centeredFrequency(index).toDouble()).toFloat()
|
||||
val power = response * response
|
||||
if (!power.isFinite()) return null
|
||||
correlation[index] = power
|
||||
energy += power.toDouble()
|
||||
}
|
||||
val meanEnergy = (energy / SPECTRUM_SIZE.toDouble()).toFloat()
|
||||
if (!(meanEnergy > 0f) || !meanEnergy.isFinite()) return null
|
||||
val inverseMeanEnergy = 1f / meanEnergy
|
||||
for (index in correlation.indices) {
|
||||
correlation[index] *= inverseMeanEnergy
|
||||
}
|
||||
|
||||
return Result(
|
||||
correlation = correlation,
|
||||
diagnosticRatio = ratio,
|
||||
outerTap = outerTap,
|
||||
centerTap = centerTap,
|
||||
)
|
||||
}
|
||||
|
||||
private fun centeredFrequency(index: Int): Float =
|
||||
(
|
||||
(index.toDouble() + 0.5) * TWO_PI / SPECTRUM_SIZE.toDouble() -
|
||||
Math.PI
|
||||
).toFloat()
|
||||
|
||||
private fun sqrtf(value: Float): Float =
|
||||
sqrt(value.toDouble()).toFloat()
|
||||
|
||||
private fun powf(
|
||||
base: Float,
|
||||
exponent: Float,
|
||||
): Float = base.toDouble().pow(exponent.toDouble()).toFloat()
|
||||
}
|
||||
@@ -72,14 +72,6 @@ internal object MgcSpatialRgbMerger {
|
||||
outputPlanarF16.limit(outputPlanarF16.capacity())
|
||||
}
|
||||
|
||||
/** Reuses the uploaded planar F16 allocation as the Spatial-noise AOT's planar Q14 input. */
|
||||
fun convertPlanarF16ToFixed16(buffer: ByteBuffer, sampleCount: Int) {
|
||||
val result = nativeConvertPlanarF16ToFixed16(buffer, sampleCount)
|
||||
check(result == 0) { "MGC planar F16-to-Q14 conversion failed with status=$result" }
|
||||
buffer.position(0)
|
||||
buffer.limit(buffer.capacity())
|
||||
}
|
||||
|
||||
private external fun nativeMerge(
|
||||
rawBuffers: Array<ByteBuffer>,
|
||||
rawOffsets: IntArray,
|
||||
@@ -107,9 +99,4 @@ internal object MgcSpatialRgbMerger {
|
||||
cfaPattern: Int,
|
||||
outputPlanarF16: ByteBuffer,
|
||||
): Int
|
||||
|
||||
private external fun nativeConvertPlanarF16ToFixed16(
|
||||
buffer: ByteBuffer,
|
||||
sampleCount: Int,
|
||||
): Int
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import com.hinnka.mycamera.raw.MgcSpatialStrengthMap
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/**
|
||||
* Thin host boundary around MGC's mechanically lifted Spatial noise-model
|
||||
* kernels. No strength approximation is performed here.
|
||||
*/
|
||||
internal object MgcSpatialStrengthMapGenerator {
|
||||
private const val TAG = "MgcSpatialStrength"
|
||||
|
||||
/**
|
||||
* Stock MGC V25 Spatial configuration value. This is an independent multiplier for
|
||||
* rejected samples; it is not derived from the sensor white level. The original call path
|
||||
* copies Context +0x2c0 into the Spatial state and forwards it to the noise-model AOT after
|
||||
* exposure normalization. The normal base-exposure path therefore uses the identity value.
|
||||
*/
|
||||
private const val REJECTED_DENOISE_MULTIPLIER = 1f
|
||||
|
||||
init {
|
||||
System.loadLibrary("my-native-lib")
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact Spatial noise-model output.
|
||||
*
|
||||
* MGC's Bayer and RGB Halide tuple order is `.0 = read variance`,
|
||||
* `.1 = shot coefficient`. The NoiseModel convenience wrapper at
|
||||
* 0x5e959c8 inserts a zero quadratic span before forwarding the original
|
||||
* two spans to the full constructor at 0x5e95688; accounting for that
|
||||
* reordering resolves the original caller at 0x3632544..0x36325fc.
|
||||
* The two diagnostic tuples feed the Savannah correlation reconstruction
|
||||
* at 0x3632688..0x3632eb4.
|
||||
* Both arrays are normalized, un-white-balanced camera RGB in R/G/B order.
|
||||
*/
|
||||
data class Result(
|
||||
val strengthMap: MgcSpatialStrengthMap,
|
||||
val outputReadNoise: FloatArray,
|
||||
val outputShotNoise: FloatArray,
|
||||
val outputWeightsSumTotalDiag0: FloatArray,
|
||||
val outputWeightsSumTotalDiag1: FloatArray,
|
||||
)
|
||||
|
||||
fun compute(
|
||||
outputMode: MgcSpatialOutputMode,
|
||||
fusedFixed16: ByteBuffer,
|
||||
width: Int,
|
||||
height: Int,
|
||||
cfaPattern: Int,
|
||||
alignment: ByteBuffer,
|
||||
alignmentWidth: Int,
|
||||
alignmentHeight: Int,
|
||||
rejection: ByteBuffer,
|
||||
rejectionWidth: Int,
|
||||
rejectionHeight: Int,
|
||||
frameCount: Int,
|
||||
inputReadNoise: FloatArray,
|
||||
inputShotNoise: FloatArray,
|
||||
frameWeights: FloatArray,
|
||||
kernelSigmas: FloatArray,
|
||||
): Result? {
|
||||
val geometry = runCatching {
|
||||
mgcSpatialDiagnosticGeometry(outputMode, width, height)
|
||||
}.getOrNull() ?: return null
|
||||
val expectedAlignmentValues =
|
||||
alignmentWidth.toLong() * alignmentHeight.toLong() * frameCount * 2L
|
||||
val expectedRejectionValues =
|
||||
rejectionWidth.toLong() * rejectionHeight.toLong() * frameCount
|
||||
val valid = fusedFixed16.isDirect && alignment.isDirect && rejection.isDirect &&
|
||||
width > 0 && height > 0 && cfaPattern in 0..3 && frameCount > 1 &&
|
||||
fusedFixed16.capacity().toLong() >=
|
||||
geometry.fixed16SampleCount * Short.SIZE_BYTES &&
|
||||
alignmentWidth == geometry.alignmentWidth &&
|
||||
alignmentHeight == geometry.alignmentHeight &&
|
||||
rejectionWidth == geometry.rejectionWidth &&
|
||||
rejectionHeight == geometry.rejectionHeight &&
|
||||
alignment.capacity().toLong() >= expectedAlignmentValues * Float.SIZE_BYTES &&
|
||||
rejection.capacity().toLong() >= expectedRejectionValues &&
|
||||
inputReadNoise.size == frameCount * 3 &&
|
||||
inputShotNoise.size == frameCount * 3 &&
|
||||
frameWeights.size == frameCount &&
|
||||
kernelSigmas.size == frameCount &&
|
||||
inputReadNoise.indices.all { index ->
|
||||
val read = inputReadNoise[index]
|
||||
val shot = inputShotNoise[index]
|
||||
read.isFinite() && read >= 0f && shot.isFinite() && shot >= 0f &&
|
||||
(read > 0f || shot > 0f)
|
||||
} &&
|
||||
frameWeights.all { it.isFinite() && it > 0f } &&
|
||||
kernelSigmas.all { it.isFinite() && it > 0f }
|
||||
if (!valid) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"Rejected malformed MGC strength input: mode=$outputMode " +
|
||||
"image=${width}x$height frames=$frameCount " +
|
||||
"alignment=${alignmentWidth}x$alignmentHeight " +
|
||||
"rejection=${rejectionWidth}x$rejectionHeight",
|
||||
)
|
||||
return null
|
||||
}
|
||||
fusedFixed16.position(0)
|
||||
alignment.position(0)
|
||||
rejection.position(0)
|
||||
val output = ShortArray(rejectionWidth * rejectionHeight)
|
||||
val outputReadNoise = FloatArray(3)
|
||||
val outputShotNoise = FloatArray(3)
|
||||
val outputWeightsSumTotalDiag0 = FloatArray(3)
|
||||
val outputWeightsSumTotalDiag1 = FloatArray(3)
|
||||
val result = nativeCompute(
|
||||
layout = if (outputMode == MgcSpatialOutputMode.BAYER) 0 else 1,
|
||||
fusedFixed16 = fusedFixed16,
|
||||
width = width,
|
||||
height = height,
|
||||
cfaPattern = cfaPattern,
|
||||
alignment = alignment,
|
||||
alignmentWidth = alignmentWidth,
|
||||
alignmentHeight = alignmentHeight,
|
||||
rejection = rejection,
|
||||
rejectionWidth = rejectionWidth,
|
||||
rejectionHeight = rejectionHeight,
|
||||
frameCount = frameCount,
|
||||
inputReadNoise = inputReadNoise,
|
||||
inputShotNoise = inputShotNoise,
|
||||
frameWeights = frameWeights,
|
||||
kernelSigmas = kernelSigmas,
|
||||
rejectedDenoiseMultiplier = REJECTED_DENOISE_MULTIPLIER,
|
||||
outputStrengthQ8 = output,
|
||||
outputReadNoise = outputReadNoise,
|
||||
outputShotNoise = outputShotNoise,
|
||||
outputWeightsSumTotalDiag0 = outputWeightsSumTotalDiag0,
|
||||
outputWeightsSumTotalDiag1 = outputWeightsSumTotalDiag1,
|
||||
)
|
||||
fusedFixed16.position(0)
|
||||
alignment.position(0)
|
||||
rejection.position(0)
|
||||
if (result != 0) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"MGC strength AOT failed: result=$result mode=$outputMode " +
|
||||
"image=${width}x$height frames=$frameCount",
|
||||
)
|
||||
return null
|
||||
}
|
||||
if (outputReadNoise.any { !it.isFinite() || it < 0f } ||
|
||||
outputShotNoise.any { !it.isFinite() || it < 0f } ||
|
||||
(0 until 3).any { channel ->
|
||||
outputReadNoise[channel] <= 0f && outputShotNoise[channel] <= 0f
|
||||
} ||
|
||||
outputWeightsSumTotalDiag0.any { !it.isFinite() || it < 0f } ||
|
||||
outputWeightsSumTotalDiag1.any { !it.isFinite() || it < 0f }
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"MGC strength AOT returned malformed output noise: " +
|
||||
"read=${outputReadNoise.contentToString()} " +
|
||||
"shot=${outputShotNoise.contentToString()} " +
|
||||
"diag0=${outputWeightsSumTotalDiag0.contentToString()} " +
|
||||
"diag1=${outputWeightsSumTotalDiag1.contentToString()}",
|
||||
)
|
||||
return null
|
||||
}
|
||||
return Result(
|
||||
strengthMap = MgcSpatialStrengthMap(
|
||||
width = rejectionWidth,
|
||||
height = rejectionHeight,
|
||||
q8 = output,
|
||||
),
|
||||
outputReadNoise = outputReadNoise,
|
||||
outputShotNoise = outputShotNoise,
|
||||
outputWeightsSumTotalDiag0 = outputWeightsSumTotalDiag0,
|
||||
outputWeightsSumTotalDiag1 = outputWeightsSumTotalDiag1,
|
||||
)
|
||||
}
|
||||
|
||||
private external fun nativeCompute(
|
||||
layout: Int,
|
||||
fusedFixed16: ByteBuffer,
|
||||
width: Int,
|
||||
height: Int,
|
||||
cfaPattern: Int,
|
||||
alignment: ByteBuffer,
|
||||
alignmentWidth: Int,
|
||||
alignmentHeight: Int,
|
||||
rejection: ByteBuffer,
|
||||
rejectionWidth: Int,
|
||||
rejectionHeight: Int,
|
||||
frameCount: Int,
|
||||
inputReadNoise: FloatArray,
|
||||
inputShotNoise: FloatArray,
|
||||
frameWeights: FloatArray,
|
||||
kernelSigmas: FloatArray,
|
||||
rejectedDenoiseMultiplier: Float,
|
||||
outputStrengthQ8: ShortArray,
|
||||
outputReadNoise: FloatArray,
|
||||
outputShotNoise: FloatArray,
|
||||
outputWeightsSumTotalDiag0: FloatArray,
|
||||
outputWeightsSumTotalDiag1: FloatArray,
|
||||
): Int
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import com.hinnka.mycamera.raw.MgcSpatialStrengthMap
|
||||
|
||||
/** Host-side resampling around the untouched MGC Spatial strength AOT output. */
|
||||
internal object MgcSpatialStrengthMapScaler {
|
||||
init {
|
||||
System.loadLibrary("my-native-lib")
|
||||
}
|
||||
|
||||
fun scaleBilinear(
|
||||
source: MgcSpatialStrengthMap,
|
||||
targetWidth: Int,
|
||||
targetHeight: Int,
|
||||
): MgcSpatialStrengthMap {
|
||||
require(targetWidth > 0 && targetHeight > 0)
|
||||
if (source.width == targetWidth && source.height == targetHeight) return source
|
||||
val targetCount = targetWidth.toLong() * targetHeight
|
||||
require(targetCount <= Int.MAX_VALUE)
|
||||
val output = ShortArray(targetCount.toInt())
|
||||
check(
|
||||
nativeScaleBilinearU16(
|
||||
source = source.q8,
|
||||
sourceWidth = source.width,
|
||||
sourceHeight = source.height,
|
||||
destination = output,
|
||||
destinationWidth = targetWidth,
|
||||
destinationHeight = targetHeight,
|
||||
)
|
||||
) {
|
||||
"Unable to scale MGC Spatial strength map " +
|
||||
"${source.width}x${source.height} to ${targetWidth}x$targetHeight"
|
||||
}
|
||||
return MgcSpatialStrengthMap(targetWidth, targetHeight, output)
|
||||
}
|
||||
|
||||
private external fun nativeScaleBilinearU16(
|
||||
source: ShortArray,
|
||||
sourceWidth: Int,
|
||||
sourceHeight: Int,
|
||||
destination: ShortArray,
|
||||
destinationWidth: Int,
|
||||
destinationHeight: Int,
|
||||
): Boolean
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import com.hinnka.mycamera.camera.AspectRatio
|
||||
import com.hinnka.mycamera.camera.MultiFrameConfig
|
||||
import com.hinnka.mycamera.model.SafeImage
|
||||
import com.hinnka.mycamera.raw.DngProfileGainTableMap
|
||||
import com.hinnka.mycamera.raw.MgcSpatialStrengthMap
|
||||
import com.hinnka.mycamera.raw.RawDenoiseHistory
|
||||
import com.hinnka.mycamera.raw.RawProfileToneMapMode
|
||||
import com.hinnka.mycamera.raw.RawSceneAERawStats
|
||||
import com.hinnka.mycamera.utils.BitmapUtils
|
||||
@@ -108,29 +108,10 @@ data class RawStackResult(
|
||||
val lensShadingCorrectionApplied: Boolean = false,
|
||||
val mergedFrameCount: Int = 1,
|
||||
/**
|
||||
* MGC's normalized 128-bin merged NoiseModel correlation spectrum.
|
||||
*
|
||||
* Null means the merged model is unavailable; a requested default merge-denoise pass must fail.
|
||||
* Merge variance ratios of the output relative to the reference frame's noise profile
|
||||
* (docs/photon-multiscale-denoise.md §2.2); null when the merge did not report them.
|
||||
*/
|
||||
val mgcDenoiseCorrelation: FloatArray? = null,
|
||||
/**
|
||||
* Normalized camera-RGB read variance emitted by the selected MGC merge branch.
|
||||
*/
|
||||
val mgcDenoiseReadNoise: FloatArray? = null,
|
||||
/**
|
||||
* Normalized camera-RGB shot coefficient emitted by the selected MGC merge branch.
|
||||
*/
|
||||
val mgcDenoiseShotNoise: FloatArray? = null,
|
||||
/**
|
||||
* Exact process-local Q8 variance multiplier emitted by MGC Spatial and consumed before
|
||||
* DNG write.
|
||||
*/
|
||||
val mgcSpatialStrengthMap: MgcSpatialStrengthMap? = null,
|
||||
/**
|
||||
* Merged output-frame SNR used by MGC FinishRaw to select luma/chroma tuning.
|
||||
* This is the linear signal-domain SNR, not ISO or sensor gain.
|
||||
*/
|
||||
val mgcDenoiseTuningSnr: Float? = null,
|
||||
val denoiseHistory: RawDenoiseHistory? = null,
|
||||
/** Reference-frame SNR for original MGC sharpen curve selection; not the merged SNR. */
|
||||
val mgcSharpenTuningSnr: Float? = null,
|
||||
/** MGC-derived attenuation applied to the final sharpen kernel. */
|
||||
|
||||
@@ -1,252 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
|
||||
|
||||
/** Generates the shared synthetic Bayer noise field directly in the calibration RAW texture. */
|
||||
internal class DemosaicNoiseAtlasGenerator {
|
||||
private var program = 0
|
||||
|
||||
fun initialize(): Boolean = getOrCreateProgram() != 0
|
||||
|
||||
fun generate(
|
||||
targetTextureId: Int,
|
||||
cfaPattern: Int,
|
||||
calculationWb: FloatArray,
|
||||
inputRead: FloatArray,
|
||||
inputShot: FloatArray,
|
||||
referenceSignals: FloatArray,
|
||||
readOnlySlot: Int,
|
||||
sampleSize: Int,
|
||||
): Boolean {
|
||||
require(targetTextureId != 0)
|
||||
require(calculationWb.size == 3)
|
||||
require(inputRead.size == 3)
|
||||
require(inputShot.size == 3)
|
||||
require(referenceSignals.size == SAMPLE_COUNT)
|
||||
require(readOnlySlot in referenceSignals.indices)
|
||||
require(sampleSize > 0)
|
||||
|
||||
val activeProgram = getOrCreateProgram()
|
||||
if (activeProgram == 0) return false
|
||||
|
||||
GLES31.glUseProgram(activeProgram)
|
||||
GLES31.glBindImageTexture(
|
||||
0,
|
||||
targetTextureId,
|
||||
0,
|
||||
false,
|
||||
0,
|
||||
GLES31.GL_WRITE_ONLY,
|
||||
GLES30.GL_RGBA16UI,
|
||||
)
|
||||
try {
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uCfaPattern"),
|
||||
cfaPattern,
|
||||
)
|
||||
GLES31.glUniform3fv(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uCalculationWb"),
|
||||
1,
|
||||
calculationWb,
|
||||
0,
|
||||
)
|
||||
GLES31.glUniform3fv(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uInputRead"),
|
||||
1,
|
||||
inputRead,
|
||||
0,
|
||||
)
|
||||
GLES31.glUniform3fv(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uInputShot"),
|
||||
1,
|
||||
inputShot,
|
||||
0,
|
||||
)
|
||||
GLES31.glUniform4fv(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uReferenceSignals"),
|
||||
1,
|
||||
referenceSignals,
|
||||
0,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uReadOnlySlot"),
|
||||
readOnlySlot,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uSampleSize"),
|
||||
sampleSize,
|
||||
)
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount((sampleSize + 1) / 2),
|
||||
GlesComputeWorkGroup.imageGroupCount(sampleSize),
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
|
||||
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT,
|
||||
)
|
||||
val error = GLES31.glGetError()
|
||||
check(error == GLES31.GL_NO_ERROR) {
|
||||
"Synthetic demosaic noise atlas generation failed with GL error " +
|
||||
"0x${error.toString(16)}"
|
||||
}
|
||||
return true
|
||||
} finally {
|
||||
GLES31.glBindImageTexture(
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
false,
|
||||
0,
|
||||
GLES31.GL_WRITE_ONLY,
|
||||
GLES30.GL_RGBA16UI,
|
||||
)
|
||||
GLES31.glUseProgram(0)
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (program != 0) {
|
||||
GLES31.glDeleteProgram(program)
|
||||
program = 0
|
||||
}
|
||||
}
|
||||
|
||||
private fun getOrCreateProgram(): Int {
|
||||
if (program == 0) {
|
||||
program = RawGlesProgram.compileCompute(COMPUTE_SHADER, "DemosaicNoiseAtlas")
|
||||
}
|
||||
return program
|
||||
}
|
||||
|
||||
private companion object {
|
||||
private const val SAMPLE_COUNT = 4
|
||||
|
||||
private val COMPUTE_SHADER = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp uimage2D;
|
||||
|
||||
layout(local_size_x = 8, local_size_y = 8) in;
|
||||
layout(rgba16ui, binding = 0) writeonly uniform highp uimage2D uOutput;
|
||||
|
||||
uniform int uCfaPattern;
|
||||
uniform vec3 uCalculationWb;
|
||||
uniform vec3 uInputRead;
|
||||
uniform vec3 uInputShot;
|
||||
uniform vec4 uReferenceSignals;
|
||||
uniform int uReadOnlySlot;
|
||||
uniform int uSampleSize;
|
||||
|
||||
uint hashBits(uint value) {
|
||||
value ^= value >> 16;
|
||||
value *= 0x7feb352du;
|
||||
value ^= value >> 15;
|
||||
value *= 0x846ca68bu;
|
||||
value ^= value >> 16;
|
||||
return value;
|
||||
}
|
||||
|
||||
float uniformOpen01(uint value) {
|
||||
return (float(hashBits(value) & 0x007fffffu) + 0.5) / 8388608.0;
|
||||
}
|
||||
|
||||
vec2 standardNormalPair(ivec2 pairPosition) {
|
||||
int pairsPerRow = (uSampleSize + 1) / 2;
|
||||
uint pairIndex = uint(pairPosition.y * pairsPerRow + pairPosition.x);
|
||||
float first = uniformOpen01(pairIndex * 2u + 0x68bc21ebu);
|
||||
float second = uniformOpen01(pairIndex * 2u + 0x02e5be93u);
|
||||
float radius = sqrt(-2.0 * log(first));
|
||||
float angle = 6.283185307179586 * second;
|
||||
return radius * vec2(cos(angle), sin(angle));
|
||||
}
|
||||
|
||||
int expandedBlockSize(int cfaPattern) {
|
||||
if (cfaPattern >= 8 && cfaPattern <= 11) return 4;
|
||||
if (cfaPattern >= 4 && cfaPattern <= 7) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int baseBayerPattern(int cfaPattern) {
|
||||
if (cfaPattern >= 8 && cfaPattern <= 11) return cfaPattern - 8;
|
||||
if (cfaPattern >= 4 && cfaPattern <= 7) return cfaPattern - 4;
|
||||
return clamp(cfaPattern, 0, 3);
|
||||
}
|
||||
|
||||
int bayerChannelIndex(int cfaPattern, int xParity, int yParity) {
|
||||
if (cfaPattern == 1) {
|
||||
if (yParity == 0 && xParity == 0) return 1;
|
||||
if (yParity == 0 && xParity == 1) return 0;
|
||||
if (yParity == 1 && xParity == 0) return 3;
|
||||
return 2;
|
||||
}
|
||||
if (cfaPattern == 2) {
|
||||
if (yParity == 0 && xParity == 0) return 2;
|
||||
if (yParity == 0 && xParity == 1) return 3;
|
||||
if (yParity == 1 && xParity == 0) return 0;
|
||||
return 1;
|
||||
}
|
||||
if (cfaPattern == 3) {
|
||||
if (yParity == 0 && xParity == 0) return 3;
|
||||
if (yParity == 0 && xParity == 1) return 2;
|
||||
if (yParity == 1 && xParity == 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
if (yParity == 0 && xParity == 0) return 0;
|
||||
if (yParity == 0 && xParity == 1) return 1;
|
||||
if (yParity == 1 && xParity == 0) return 2;
|
||||
return 3;
|
||||
}
|
||||
|
||||
int rgbChannelForPixel(ivec2 position) {
|
||||
int blockSize = expandedBlockSize(uCfaPattern);
|
||||
int bayerChannel = bayerChannelIndex(
|
||||
baseBayerPattern(uCfaPattern),
|
||||
(position.x / blockSize) & 1,
|
||||
(position.y / blockSize) & 1
|
||||
);
|
||||
if (bayerChannel == 0) return 0;
|
||||
if (bayerChannel == 3) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
void writeSamples(ivec2 position, float gaussian) {
|
||||
int channel = rgbChannelForPixel(position);
|
||||
float wb = max(uCalculationWb[channel], 1e-6);
|
||||
vec4 rawSignals = uReferenceSignals / wb;
|
||||
vec4 variances =
|
||||
vec4(uInputRead[channel]) + uInputShot[channel] * rawSignals;
|
||||
variances[uReadOnlySlot] = uInputRead[channel];
|
||||
vec4 noisy = clamp(
|
||||
rawSignals + sqrt(max(variances, vec4(0.0))) * gaussian,
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
for (int slot = 0; slot < 4; ++slot) {
|
||||
uint quantized = uint(floor(noisy[slot] * 65535.0 + 0.5));
|
||||
imageStore(
|
||||
uOutput,
|
||||
position + ivec2(slot * uSampleSize, 0),
|
||||
uvec4(quantized, 0u, 0u, 1u)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 pairPosition = ivec2(gl_GlobalInvocationID.xy);
|
||||
ivec2 firstPosition = ivec2(pairPosition.x * 2, pairPosition.y);
|
||||
if (any(greaterThanEqual(firstPosition, ivec2(uSampleSize)))) return;
|
||||
|
||||
vec2 gaussian = standardNormalPair(pairPosition);
|
||||
writeSamples(firstPosition, gaussian.x);
|
||||
ivec2 secondPosition = firstPosition + ivec2(1, 0);
|
||||
if (secondPosition.x < uSampleSize) {
|
||||
writeSamples(secondPosition, gaussian.y);
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
@@ -1,913 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import android.util.Half
|
||||
import com.hinnka.mycamera.processor.PhotonCoreImagingTuning
|
||||
import com.hinnka.mycamera.utils.LargeDirectBuffer
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
|
||||
internal typealias DemosaicNoiseTransfer = MgcFullResolutionDenoise.PreparedYuvNoiseModel
|
||||
|
||||
internal data class DemosaicNoiseRenderRequest(
|
||||
val metadata: RawMetadata,
|
||||
val rawTextureId: Int,
|
||||
val linearOutputTextureId: Int,
|
||||
val outputTextureId: Int,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
)
|
||||
|
||||
/** Computes the legacy half-bin luma/chroma spectrum in O(N log N) instead of direct O(N²). */
|
||||
internal object DemosaicNoiseSpectrum {
|
||||
const val SIZE = 128
|
||||
|
||||
fun propagatedCorrelation(
|
||||
residuals: Array<FloatArray>,
|
||||
channels: IntArray,
|
||||
inputCorrelation: FloatArray,
|
||||
): FloatArray? {
|
||||
if (inputCorrelation.size != SIZE ||
|
||||
inputCorrelation.any { !it.isFinite() || it < 0f }
|
||||
) return null
|
||||
val inputMean = inputCorrelation.average()
|
||||
if (inputMean == 0.0) return FloatArray(SIZE)
|
||||
val demosaicPower = halfBinDirectionalPower(residuals, channels)
|
||||
val demosaicPowerMean = demosaicPower.average()
|
||||
if (!demosaicPowerMean.isFinite() || demosaicPowerMean <= 0.0) return null
|
||||
val composed = DoubleArray(SIZE) { index ->
|
||||
inputCorrelation[index].toDouble() *
|
||||
(demosaicPower[index] / demosaicPowerMean)
|
||||
}
|
||||
val compositionMean = composed.average()
|
||||
if (!compositionMean.isFinite() || compositionMean <= 0.0) return null
|
||||
// Synthetic calibration measures demosaic transfer using read/shot coefficients,
|
||||
// without the input spectrum. Normalize only the composed shape: discarding the
|
||||
// input amplitude here would erase a non-unit NoiseModel constructor seed.
|
||||
return FloatArray(SIZE) { index ->
|
||||
(composed[index] / compositionMean * inputMean).toFloat()
|
||||
}.takeIf { spectrum -> spectrum.all { it.isFinite() && it >= 0f } }
|
||||
}
|
||||
|
||||
internal fun halfBinDirectionalPower(
|
||||
residuals: Array<FloatArray>,
|
||||
channels: IntArray,
|
||||
): DoubleArray {
|
||||
require(channels.all { it in residuals.indices })
|
||||
require(channels.all { residuals[it].size == SIZE * SIZE })
|
||||
val power = DoubleArray(SIZE)
|
||||
val real = DoubleArray(SIZE)
|
||||
val imaginary = DoubleArray(SIZE)
|
||||
for (channel in channels) {
|
||||
val residual = residuals[channel]
|
||||
for (line in 0 until SIZE) {
|
||||
fillShiftedLine(
|
||||
residual = residual,
|
||||
line = line,
|
||||
vertical = false,
|
||||
real = real,
|
||||
imaginary = imaginary,
|
||||
)
|
||||
forwardFft(real, imaginary)
|
||||
accumulateMappedPower(real, imaginary, power)
|
||||
|
||||
fillShiftedLine(
|
||||
residual = residual,
|
||||
line = line,
|
||||
vertical = true,
|
||||
real = real,
|
||||
imaginary = imaginary,
|
||||
)
|
||||
forwardFft(real, imaginary)
|
||||
accumulateMappedPower(real, imaginary, power)
|
||||
}
|
||||
}
|
||||
val normalization = 2.0 * SIZE * SIZE
|
||||
for (bin in power.indices) power[bin] /= normalization
|
||||
return power
|
||||
}
|
||||
|
||||
private fun fillShiftedLine(
|
||||
residual: FloatArray,
|
||||
line: Int,
|
||||
vertical: Boolean,
|
||||
real: DoubleArray,
|
||||
imaginary: DoubleArray,
|
||||
) {
|
||||
for (position in 0 until SIZE) {
|
||||
val value = if (vertical) {
|
||||
residual[position * SIZE + line]
|
||||
} else {
|
||||
residual[line * SIZE + position]
|
||||
}.toDouble()
|
||||
real[position] = value * HALF_BIN_SHIFT_COSINE[position]
|
||||
imaginary[position] = value * HALF_BIN_SHIFT_SINE[position]
|
||||
}
|
||||
}
|
||||
|
||||
private fun accumulateMappedPower(
|
||||
real: DoubleArray,
|
||||
imaginary: DoubleArray,
|
||||
power: DoubleArray,
|
||||
) {
|
||||
for (bin in 0 until SIZE) {
|
||||
// The legacy frequency is 2π(bin + 0.5)/N - π. Premultiplication supplies the
|
||||
// half-bin shift; this rotation maps the centered legacy order to FFT order.
|
||||
val fftIndex = (bin + SIZE / 2) and (SIZE - 1)
|
||||
power[bin] +=
|
||||
real[fftIndex] * real[fftIndex] +
|
||||
imaginary[fftIndex] * imaginary[fftIndex]
|
||||
}
|
||||
}
|
||||
|
||||
private fun forwardFft(real: DoubleArray, imaginary: DoubleArray) {
|
||||
var reversed = 0
|
||||
for (index in 1 until SIZE) {
|
||||
var bit = SIZE shr 1
|
||||
while (reversed and bit != 0) {
|
||||
reversed = reversed xor bit
|
||||
bit = bit shr 1
|
||||
}
|
||||
reversed = reversed xor bit
|
||||
if (index < reversed) {
|
||||
val realSwap = real[index]
|
||||
real[index] = real[reversed]
|
||||
real[reversed] = realSwap
|
||||
val imaginarySwap = imaginary[index]
|
||||
imaginary[index] = imaginary[reversed]
|
||||
imaginary[reversed] = imaginarySwap
|
||||
}
|
||||
}
|
||||
|
||||
var length = 2
|
||||
while (length <= SIZE) {
|
||||
val halfLength = length / 2
|
||||
val twiddleStep = SIZE / length
|
||||
var block = 0
|
||||
while (block < SIZE) {
|
||||
for (offset in 0 until halfLength) {
|
||||
val twiddleIndex = offset * twiddleStep
|
||||
val twiddleReal = FFT_COSINE[twiddleIndex]
|
||||
val twiddleImaginary = FFT_SINE[twiddleIndex]
|
||||
val evenIndex = block + offset
|
||||
val oddIndex = evenIndex + halfLength
|
||||
val oddReal =
|
||||
real[oddIndex] * twiddleReal -
|
||||
imaginary[oddIndex] * twiddleImaginary
|
||||
val oddImaginary =
|
||||
real[oddIndex] * twiddleImaginary +
|
||||
imaginary[oddIndex] * twiddleReal
|
||||
val evenReal = real[evenIndex]
|
||||
val evenImaginary = imaginary[evenIndex]
|
||||
real[evenIndex] = evenReal + oddReal
|
||||
imaginary[evenIndex] = evenImaginary + oddImaginary
|
||||
real[oddIndex] = evenReal - oddReal
|
||||
imaginary[oddIndex] = evenImaginary - oddImaginary
|
||||
}
|
||||
block += length
|
||||
}
|
||||
length = length shl 1
|
||||
}
|
||||
}
|
||||
|
||||
private val HALF_BIN_SHIFT_COSINE =
|
||||
DoubleArray(SIZE) { position -> cos(-PI * position / SIZE) }
|
||||
private val HALF_BIN_SHIFT_SINE =
|
||||
DoubleArray(SIZE) { position -> sin(-PI * position / SIZE) }
|
||||
private val FFT_COSINE =
|
||||
DoubleArray(SIZE / 2) { index -> cos(-2.0 * PI * index / SIZE) }
|
||||
private val FFT_SINE =
|
||||
DoubleArray(SIZE / 2) { index -> sin(-2.0 * PI * index / SIZE) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures how the active demosaic pipeline propagates physical Bayer noise into MGC's YUV
|
||||
* domain. The calibrator owns the synthetic fields, GL calibration resources, model fitting and
|
||||
* cache; [RawDemosaicProcessor] only supplies pipeline initialization and one demosaic dispatch.
|
||||
*/
|
||||
internal class DemosaicNoisePropagationCalibrator(
|
||||
private val initializePipeline: (cfaPattern: Int) -> Boolean,
|
||||
private val renderDemosaic: (DemosaicNoiseRenderRequest) -> Unit,
|
||||
) {
|
||||
private data class NoiseSample(
|
||||
val referenceSignal: Float,
|
||||
val workingLumaMean: Float,
|
||||
val normalizedYuvVariance: FloatArray,
|
||||
val lumaCorrelation: FloatArray?,
|
||||
val chromaCorrelation: FloatArray?,
|
||||
)
|
||||
|
||||
private data class CacheKey(
|
||||
val cfaPattern: Int,
|
||||
val normalizedRgbReadBits: List<Int>,
|
||||
val normalizedRgbShotBits: List<Int>,
|
||||
val inputCorrelationBits: List<Int>,
|
||||
val calculationWbBits: List<Int>,
|
||||
)
|
||||
|
||||
private enum class NoiseComponent {
|
||||
TOTAL,
|
||||
READ_ONLY,
|
||||
}
|
||||
|
||||
private data class NoiseSampleSpec(
|
||||
val referenceSignal: Float,
|
||||
val component: NoiseComponent,
|
||||
val includeCorrelation: Boolean,
|
||||
)
|
||||
|
||||
private data class GlRenderTiming(
|
||||
val atlasGenerationSubmitMs: Long,
|
||||
val demosaicMs: Long,
|
||||
val readbackMs: Long,
|
||||
)
|
||||
|
||||
private class AnalysisWorkspace {
|
||||
val workingRgb = Array(3) { FloatArray(ANALYSIS_PIXELS) }
|
||||
val yuvResidual = Array(3) { FloatArray(ANALYSIS_PIXELS) }
|
||||
}
|
||||
|
||||
private inner class GlCalibrationSession {
|
||||
private val textures = IntArray(3)
|
||||
private val framebuffers = IntArray(1)
|
||||
private val savedPackAlignment = glInteger(GLES30.GL_PACK_ALIGNMENT)
|
||||
private val savedFramebuffer = glInteger(GLES30.GL_FRAMEBUFFER_BINDING)
|
||||
private val savedPixelPackBuffer = glInteger(GLES30.GL_PIXEL_PACK_BUFFER_BINDING)
|
||||
private val savedActiveTexture = glInteger(GLES30.GL_ACTIVE_TEXTURE)
|
||||
private val savedTextureBinding = glInteger(GLES30.GL_TEXTURE_BINDING_2D)
|
||||
private var released = false
|
||||
val allocationMs: Long
|
||||
|
||||
private val rawTextureId: Int
|
||||
get() = textures[0]
|
||||
private val outputTextureId: Int
|
||||
get() = textures[1]
|
||||
private val linearOutputTextureId: Int
|
||||
get() = textures[2]
|
||||
private val framebufferId: Int
|
||||
get() = framebuffers[0]
|
||||
|
||||
init {
|
||||
val startNs = System.nanoTime()
|
||||
try {
|
||||
GLES30.glGenTextures(textures.size, textures, 0)
|
||||
check(textures.all { it != 0 }) {
|
||||
"Unable to allocate noise calibration textures"
|
||||
}
|
||||
|
||||
configureTexture(
|
||||
textureId = rawTextureId,
|
||||
// GLES 3.1 guarantees RGBA16UI image store. Demosaic samplers consume .r,
|
||||
// so calibration does not need a format-conversion pass back to R16UI.
|
||||
internalFormat = GLES30.GL_RGBA16UI,
|
||||
)
|
||||
configureTexture(
|
||||
textureId = outputTextureId,
|
||||
internalFormat = GLES30.GL_RGBA16F,
|
||||
)
|
||||
configureTexture(
|
||||
textureId = linearOutputTextureId,
|
||||
internalFormat = GLES30.GL_RGBA16F,
|
||||
)
|
||||
|
||||
GLES30.glGenFramebuffers(1, framebuffers, 0)
|
||||
check(framebufferId != 0) {
|
||||
"Unable to allocate noise calibration framebuffer"
|
||||
}
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebufferId)
|
||||
GLES30.glFramebufferTexture2D(
|
||||
GLES30.GL_FRAMEBUFFER,
|
||||
GLES30.GL_COLOR_ATTACHMENT0,
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
outputTextureId,
|
||||
0,
|
||||
)
|
||||
check(
|
||||
GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) ==
|
||||
GLES30.GL_FRAMEBUFFER_COMPLETE,
|
||||
) {
|
||||
"Noise calibration framebuffer is incomplete"
|
||||
}
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
checkGlError("resource allocation")
|
||||
allocationMs = elapsedMs(startNs)
|
||||
} catch (error: Throwable) {
|
||||
release()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
fun render(
|
||||
metadata: RawMetadata,
|
||||
calculationWb: FloatArray,
|
||||
inputRead: FloatArray,
|
||||
inputShot: FloatArray,
|
||||
rgbaOutput: ByteBuffer,
|
||||
): GlRenderTiming {
|
||||
val atlasGenerationStartNs = System.nanoTime()
|
||||
check(
|
||||
atlasGenerator.generate(
|
||||
targetTextureId = rawTextureId,
|
||||
cfaPattern = metadata.cfaPattern,
|
||||
calculationWb = calculationWb,
|
||||
inputRead = inputRead,
|
||||
inputShot = inputShot,
|
||||
referenceSignals = REFERENCE_SIGNALS,
|
||||
readOnlySlot = READ_ONLY_SLOT,
|
||||
sampleSize = CALIBRATION_SIZE,
|
||||
),
|
||||
) {
|
||||
"Unable to generate synthetic demosaic noise atlas"
|
||||
}
|
||||
val atlasGenerationSubmitMs = elapsedMs(atlasGenerationStartNs)
|
||||
|
||||
val demosaicStartNs = System.nanoTime()
|
||||
renderDemosaic(
|
||||
DemosaicNoiseRenderRequest(
|
||||
metadata = metadata,
|
||||
rawTextureId = rawTextureId,
|
||||
linearOutputTextureId = linearOutputTextureId,
|
||||
outputTextureId = outputTextureId,
|
||||
width = ATLAS_WIDTH,
|
||||
height = ATLAS_HEIGHT,
|
||||
),
|
||||
)
|
||||
val demosaicMs = elapsedMs(demosaicStartNs)
|
||||
|
||||
val readbackStartNs = System.nanoTime()
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
|
||||
)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebufferId)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 8)
|
||||
rgbaOutput.clear()
|
||||
GLES30.glReadPixels(
|
||||
0,
|
||||
0,
|
||||
ATLAS_WIDTH,
|
||||
ATLAS_HEIGHT,
|
||||
GLES30.GL_RGBA,
|
||||
GLES30.GL_HALF_FLOAT,
|
||||
rgbaOutput,
|
||||
)
|
||||
checkGlError("readback")
|
||||
return GlRenderTiming(
|
||||
atlasGenerationSubmitMs = atlasGenerationSubmitMs,
|
||||
demosaicMs = demosaicMs,
|
||||
readbackMs = elapsedMs(readbackStartNs),
|
||||
)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (released) return
|
||||
released = true
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
GLES30.glDeleteFramebuffers(framebuffers.size, framebuffers, 0)
|
||||
GLES30.glDeleteTextures(textures.size, textures, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, savedPackAlignment)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, savedPixelPackBuffer)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, savedFramebuffer)
|
||||
GLES30.glActiveTexture(savedActiveTexture)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, savedTextureBinding)
|
||||
}
|
||||
|
||||
private fun configureTexture(textureId: Int, internalFormat: Int) {
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
|
||||
GLES30.glTexStorage2D(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
1,
|
||||
internalFormat,
|
||||
ATLAS_WIDTH,
|
||||
ATLAS_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,
|
||||
)
|
||||
GLES30.glTexParameteri(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
GLES30.GL_TEXTURE_WRAP_S,
|
||||
GLES30.GL_CLAMP_TO_EDGE,
|
||||
)
|
||||
GLES30.glTexParameteri(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
GLES30.GL_TEXTURE_WRAP_T,
|
||||
GLES30.GL_CLAMP_TO_EDGE,
|
||||
)
|
||||
}
|
||||
|
||||
private fun glInteger(parameter: Int): Int {
|
||||
val value = IntArray(1)
|
||||
GLES30.glGetIntegerv(parameter, value, 0)
|
||||
return value[0]
|
||||
}
|
||||
}
|
||||
|
||||
private val atlasGenerator = DemosaicNoiseAtlasGenerator()
|
||||
private var cachedKey: CacheKey? = null
|
||||
private var cachedTransfer: DemosaicNoiseTransfer? = null
|
||||
|
||||
fun release() {
|
||||
atlasGenerator.release()
|
||||
cachedKey = null
|
||||
cachedTransfer = null
|
||||
}
|
||||
|
||||
fun prepareUserAdjustment(
|
||||
metadata: RawMetadata,
|
||||
calculationWb4: FloatArray,
|
||||
): DemosaicNoiseTransfer? {
|
||||
val rgbNoise = MgcFullResolutionDenoise.resolveUserAdjustmentCameraRgbNoise(metadata)
|
||||
?: return null
|
||||
val spectrumSeed = PhotonCoreImagingTuning.denoise.noiseSpectrumSeed
|
||||
val propagationMetadata = metadata.copy(
|
||||
frameCount = 1,
|
||||
mgcDenoiseReadNoise = rgbNoise.read,
|
||||
mgcDenoiseShotNoise = rgbNoise.shot,
|
||||
mgcDenoiseCorrelation = FloatArray(SPECTRUM_BINS) { spectrumSeed },
|
||||
mgcSpatialStrengthMap = null,
|
||||
)
|
||||
return measure(propagationMetadata, calculationWb4)?.also { transfer ->
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC USER_ADJUSTMENT noise propagation ready " +
|
||||
"pipeline=${pipelineLabel(metadata.cfaPattern)} " +
|
||||
"lumaCorrelation=${transfer.lumaCorrelation.minOrNull()}.." +
|
||||
"${transfer.lumaCorrelation.maxOrNull()}/${transfer.lumaCorrelation.average()} " +
|
||||
"chromaCorrelation=${transfer.chromaCorrelation.minOrNull()}.." +
|
||||
"${transfer.chromaCorrelation.maxOrNull()}/" +
|
||||
transfer.chromaCorrelation.average(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun measure(
|
||||
metadata: RawMetadata,
|
||||
calculationWb4: FloatArray,
|
||||
): DemosaicNoiseTransfer? {
|
||||
val inputRead = metadata.mgcDenoiseReadNoise
|
||||
val inputShot = metadata.mgcDenoiseShotNoise
|
||||
val inputCorrelation = metadata.mgcDenoiseCorrelation
|
||||
if (inputRead?.size != 3 || inputShot?.size != 3 ||
|
||||
inputCorrelation?.size != SPECTRUM_BINS ||
|
||||
inputRead.any { !it.isFinite() || it < 0f } ||
|
||||
inputShot.any { !it.isFinite() || it < 0f } ||
|
||||
inputCorrelation.any { !it.isFinite() || it < 0f }
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val calculationWb = floatArrayOf(
|
||||
calculationWb4.getOrElse(0) { 1f },
|
||||
1f,
|
||||
calculationWb4.getOrElse(3) { 1f },
|
||||
)
|
||||
val cacheKey = CacheKey(
|
||||
cfaPattern = metadata.cfaPattern,
|
||||
normalizedRgbReadBits = inputRead.map(Float::toBits),
|
||||
normalizedRgbShotBits = inputShot.map(Float::toBits),
|
||||
inputCorrelationBits = inputCorrelation.map(Float::toBits),
|
||||
calculationWbBits = calculationWb.map(Float::toBits),
|
||||
)
|
||||
if (cacheKey == cachedKey) {
|
||||
PLog.i(TAG, "Demosaic noise propagation cache hit pipeline=${pipelineLabel(metadata.cfaPattern)}")
|
||||
return cachedTransfer
|
||||
}
|
||||
|
||||
val totalStartNs = System.nanoTime()
|
||||
return try {
|
||||
val pipelineInitStartNs = System.nanoTime()
|
||||
check(initializePipeline(metadata.cfaPattern)) {
|
||||
"Unable to initialize ${pipelineLabel(metadata.cfaPattern)} noise propagation programs"
|
||||
}
|
||||
check(atlasGenerator.initialize()) {
|
||||
"Unable to initialize synthetic demosaic noise atlas generator"
|
||||
}
|
||||
val pipelineInitMs = elapsedMs(pipelineInitStartNs)
|
||||
val calibrationMetadata = metadata.copy(
|
||||
width = ATLAS_WIDTH,
|
||||
height = ATLAS_HEIGHT,
|
||||
// The supplied coefficients already describe the merged output frame.
|
||||
frameCount = 1,
|
||||
blackLevel = FloatArray(4),
|
||||
whiteLevel = 65535f,
|
||||
lensShadingMap = null,
|
||||
lensShadingMapWidth = 0,
|
||||
lensShadingMapHeight = 0,
|
||||
lensShadingMapGrid = null,
|
||||
channelNoiseProfile = floatArrayOf(
|
||||
inputShot[0], inputRead[0],
|
||||
inputShot[1], inputRead[1],
|
||||
inputShot[2], inputRead[2],
|
||||
),
|
||||
noiseProfileLayout = RawNoiseProfileLayout.DNG_RGB,
|
||||
)
|
||||
measureUncached(
|
||||
metadata = calibrationMetadata,
|
||||
calculationWb = calculationWb,
|
||||
inputRead = inputRead,
|
||||
inputShot = inputShot,
|
||||
inputCorrelation = inputCorrelation,
|
||||
pipelineInitMs = pipelineInitMs,
|
||||
totalStartNs = totalStartNs,
|
||||
)?.also { transfer ->
|
||||
cachedKey = cacheKey
|
||||
cachedTransfer = transfer
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"${pipelineLabel(metadata.cfaPattern)} noise propagation failed",
|
||||
error,
|
||||
)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun measureUncached(
|
||||
metadata: RawMetadata,
|
||||
calculationWb: FloatArray,
|
||||
inputRead: FloatArray,
|
||||
inputShot: FloatArray,
|
||||
inputCorrelation: FloatArray,
|
||||
pipelineInitMs: Long,
|
||||
totalStartNs: Long,
|
||||
): DemosaicNoiseTransfer? {
|
||||
val cpuSetupStartNs = System.nanoTime()
|
||||
val calibrationPixels = ATLAS_WIDTH * ATLAS_HEIGHT
|
||||
val rgba = LargeDirectBuffer.allocate(
|
||||
calibrationPixels.toLong() * 4 * Short.SIZE_BYTES,
|
||||
"Demosaic noise propagation RGBA16F atlas",
|
||||
)?.order(ByteOrder.nativeOrder()) ?: return null
|
||||
val workspace = AnalysisWorkspace()
|
||||
val cpuSetupMs = elapsedMs(cpuSetupStartNs)
|
||||
val session = try {
|
||||
GlCalibrationSession()
|
||||
} catch (error: Throwable) {
|
||||
LargeDirectBuffer.free(rgba)
|
||||
throw error
|
||||
}
|
||||
|
||||
val samples = ArrayList<NoiseSample>(SAMPLE_SPECS.size - 1)
|
||||
var readSample: NoiseSample? = null
|
||||
var renderTiming = GlRenderTiming(
|
||||
atlasGenerationSubmitMs = 0L,
|
||||
demosaicMs = 0L,
|
||||
readbackMs = 0L,
|
||||
)
|
||||
var totalAnalysisMs = 0L
|
||||
var totalCorrelationMs = 0L
|
||||
val resourceReleaseStartNs: Long
|
||||
try {
|
||||
renderTiming = session.render(
|
||||
metadata = metadata,
|
||||
calculationWb = calculationWb,
|
||||
inputRead = inputRead,
|
||||
inputShot = inputShot,
|
||||
rgbaOutput = rgba,
|
||||
)
|
||||
|
||||
SAMPLE_SPECS.forEachIndexed { slotIndex, spec ->
|
||||
val analysisStartNs = System.nanoTime()
|
||||
val analysis = analyzeOutput(
|
||||
rgba = rgba,
|
||||
atlasSlot = slotIndex,
|
||||
calculationWb = calculationWb,
|
||||
spec = spec,
|
||||
inputRead = inputRead,
|
||||
inputShot = inputShot,
|
||||
workspace = workspace,
|
||||
preserveResidual = spec.includeCorrelation,
|
||||
) ?: return null
|
||||
val analysisMs = elapsedMs(analysisStartNs)
|
||||
|
||||
val correlationStartNs = System.nanoTime()
|
||||
val lumaCorrelation = if (spec.includeCorrelation) {
|
||||
DemosaicNoiseSpectrum.propagatedCorrelation(
|
||||
residuals = workspace.yuvResidual,
|
||||
channels = intArrayOf(0),
|
||||
inputCorrelation = inputCorrelation,
|
||||
) ?: return null
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val chromaCorrelation = if (spec.includeCorrelation) {
|
||||
DemosaicNoiseSpectrum.propagatedCorrelation(
|
||||
residuals = workspace.yuvResidual,
|
||||
channels = intArrayOf(1, 2),
|
||||
inputCorrelation = inputCorrelation,
|
||||
) ?: return null
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val correlationMs = elapsedMs(correlationStartNs)
|
||||
totalAnalysisMs += analysisMs
|
||||
totalCorrelationMs += correlationMs
|
||||
|
||||
val sample = NoiseSample(
|
||||
referenceSignal = spec.referenceSignal,
|
||||
workingLumaMean = analysis.workingLumaMean,
|
||||
normalizedYuvVariance = analysis.normalizedYuvVariance,
|
||||
lumaCorrelation = lumaCorrelation,
|
||||
chromaCorrelation = chromaCorrelation,
|
||||
)
|
||||
if (spec.component == NoiseComponent.READ_ONLY) {
|
||||
readSample = sample
|
||||
} else {
|
||||
samples += sample
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Demosaic noise propagation sample " +
|
||||
"pipeline=${pipelineLabel(metadata.cfaPattern)} atlasSlot=$slotIndex " +
|
||||
"component=${spec.component} reference=${spec.referenceSignal} " +
|
||||
"correlation=${spec.includeCorrelation} " +
|
||||
"workingLumaMean=${analysis.workingLumaMean} " +
|
||||
"normalizedYuvVariance=${analysis.normalizedYuvVariance.contentToString()} " +
|
||||
"outputToTheoreticalInputVarianceRatio=" +
|
||||
"${analysis.outputToTheoreticalInputVarianceRatio.contentToString()} " +
|
||||
"analysisMs=$analysisMs correlationMs=$correlationMs",
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
resourceReleaseStartNs = System.nanoTime()
|
||||
session.release()
|
||||
LargeDirectBuffer.free(rgba)
|
||||
}
|
||||
val resourceReleaseMs = elapsedMs(resourceReleaseStartNs)
|
||||
val referenceSample = samples.first { it.referenceSignal == REFERENCE_SIGNAL }
|
||||
val lumaCorrelation = checkNotNull(referenceSample.lumaCorrelation)
|
||||
val chromaCorrelation = checkNotNull(referenceSample.chromaCorrelation)
|
||||
val fitStartNs = System.nanoTime()
|
||||
val transfer = fitTransfer(
|
||||
samples = samples,
|
||||
readSample = checkNotNull(readSample),
|
||||
lumaCorrelation = lumaCorrelation,
|
||||
chromaCorrelation = chromaCorrelation,
|
||||
) ?: return null
|
||||
val fitMs = elapsedMs(fitStartNs)
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Demosaic noise calibration timing " +
|
||||
"pipeline=${pipelineLabel(metadata.cfaPattern)} " +
|
||||
"totalMs=${elapsedMs(totalStartNs)} programInitMs=$pipelineInitMs " +
|
||||
"cpuSetupMs=$cpuSetupMs resourceAllocMs=${session.allocationMs} " +
|
||||
"atlas=${ATLAS_WIDTH}x$ATLAS_HEIGHT " +
|
||||
"atlasGenerationSubmitMs=${renderTiming.atlasGenerationSubmitMs} " +
|
||||
"demosaicMs=${renderTiming.demosaicMs} " +
|
||||
"readbackMs=${renderTiming.readbackMs} analysisMs=$totalAnalysisMs " +
|
||||
"correlationMs=$totalCorrelationMs fitMs=$fitMs " +
|
||||
"resourceReleaseMs=$resourceReleaseMs",
|
||||
)
|
||||
return transfer
|
||||
}
|
||||
|
||||
private data class OutputAnalysis(
|
||||
val workingLumaMean: Float,
|
||||
val normalizedYuvVariance: FloatArray,
|
||||
val outputToTheoreticalInputVarianceRatio: FloatArray,
|
||||
)
|
||||
|
||||
private fun analyzeOutput(
|
||||
rgba: ByteBuffer,
|
||||
atlasSlot: Int,
|
||||
calculationWb: FloatArray,
|
||||
spec: NoiseSampleSpec,
|
||||
inputRead: FloatArray,
|
||||
inputShot: FloatArray,
|
||||
workspace: AnalysisWorkspace,
|
||||
preserveResidual: Boolean,
|
||||
): OutputAnalysis? {
|
||||
val mean = DoubleArray(3)
|
||||
var sampleIndex = 0
|
||||
for (y in 0 until ANALYSIS_SIZE) {
|
||||
val sourceY = ANALYSIS_ORIGIN + y
|
||||
for (x in 0 until ANALYSIS_SIZE) {
|
||||
val sourceX = atlasSlot * CALIBRATION_SIZE + ANALYSIS_ORIGIN + x
|
||||
val pixelOffset =
|
||||
(sourceY * ATLAS_WIDTH + sourceX) * 4 * Short.SIZE_BYTES
|
||||
for (channel in 0 until 3) {
|
||||
val value = Half.toFloat(
|
||||
rgba.getShort(pixelOffset + channel * Short.SIZE_BYTES),
|
||||
) * calculationWb[channel]
|
||||
workspace.workingRgb[channel][sampleIndex] = value
|
||||
mean[channel] += value
|
||||
}
|
||||
sampleIndex++
|
||||
}
|
||||
}
|
||||
for (channel in 0 until 3) mean[channel] /= ANALYSIS_PIXELS.toDouble()
|
||||
var workingLumaMean = 0.0
|
||||
for (channel in 0 until 3) {
|
||||
workingLumaMean += RGB_TO_YUV[channel] * mean[channel]
|
||||
}
|
||||
|
||||
val outputVariance = DoubleArray(3)
|
||||
val yuvVariance = DoubleArray(3)
|
||||
for (index in 0 until ANALYSIS_PIXELS) {
|
||||
val red = workspace.workingRgb[0][index] - mean[0].toFloat()
|
||||
val green = workspace.workingRgb[1][index] - mean[1].toFloat()
|
||||
val blue = workspace.workingRgb[2][index] - mean[2].toFloat()
|
||||
outputVariance[0] += red * red
|
||||
outputVariance[1] += green * green
|
||||
outputVariance[2] += blue * blue
|
||||
for (outputChannel in 0 until 3) {
|
||||
val offset = outputChannel * 3
|
||||
val residual =
|
||||
RGB_TO_YUV[offset] * red +
|
||||
RGB_TO_YUV[offset + 1] * green +
|
||||
RGB_TO_YUV[offset + 2] * blue
|
||||
yuvVariance[outputChannel] += residual * residual
|
||||
if (preserveResidual) workspace.yuvResidual[outputChannel][index] = residual
|
||||
}
|
||||
}
|
||||
val outputToTheoreticalInputVarianceRatio = FloatArray(3)
|
||||
for (channel in 0 until 3) {
|
||||
outputVariance[channel] /= ANALYSIS_PIXELS.toDouble()
|
||||
val wb = calculationWb[channel].coerceAtLeast(1e-6f).toDouble()
|
||||
val rawSignal = spec.referenceSignal.toDouble() / wb
|
||||
val rawVariance = when (spec.component) {
|
||||
NoiseComponent.TOTAL ->
|
||||
inputRead[channel].toDouble() + inputShot[channel] * rawSignal
|
||||
NoiseComponent.READ_ONLY -> inputRead[channel].toDouble()
|
||||
}
|
||||
val theoreticalWorkingVariance = rawVariance * wb * wb
|
||||
if (!theoreticalWorkingVariance.isFinite() || theoreticalWorkingVariance <= 0.0 ||
|
||||
!outputVariance[channel].isFinite() || outputVariance[channel] <= 0.0
|
||||
) {
|
||||
return null
|
||||
}
|
||||
outputToTheoreticalInputVarianceRatio[channel] =
|
||||
(outputVariance[channel] / theoreticalWorkingVariance).toFloat()
|
||||
}
|
||||
val normalizedYuvVariance = FloatArray(3) { channel ->
|
||||
(yuvVariance[channel] / ANALYSIS_PIXELS.toDouble()).toFloat()
|
||||
}
|
||||
if (!workingLumaMean.isFinite() || workingLumaMean <= 0.0 ||
|
||||
normalizedYuvVariance.any { !it.isFinite() || it <= 0f }
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return OutputAnalysis(
|
||||
workingLumaMean = workingLumaMean.toFloat(),
|
||||
normalizedYuvVariance = normalizedYuvVariance,
|
||||
outputToTheoreticalInputVarianceRatio = outputToTheoreticalInputVarianceRatio,
|
||||
)
|
||||
}
|
||||
|
||||
private fun fitTransfer(
|
||||
samples: List<NoiseSample>,
|
||||
readSample: NoiseSample,
|
||||
lumaCorrelation: FloatArray,
|
||||
chromaCorrelation: FloatArray,
|
||||
): DemosaicNoiseTransfer? {
|
||||
val fittedRead = readSample.normalizedYuvVariance.copyOf()
|
||||
val fittedShot = FloatArray(3)
|
||||
val fittedQuadratic = FloatArray(3)
|
||||
val fitTerms = Array(3) { "none" }
|
||||
val relativeFitError = FloatArray(3)
|
||||
val signals = samples.map { it.workingLumaMean.toDouble() }.toDoubleArray()
|
||||
for (channel in 0 until 3) {
|
||||
val variances = samples
|
||||
.map { it.normalizedYuvVariance[channel].toDouble() }
|
||||
.toDoubleArray()
|
||||
val fit = fitNonNegativeNoisePolynomial(
|
||||
signals,
|
||||
variances,
|
||||
fixedRead = fittedRead[channel].toDouble(),
|
||||
) ?: return null
|
||||
fittedShot[channel] = fit.shot.toFloat()
|
||||
fittedQuadratic[channel] = fit.quadratic.toFloat()
|
||||
fitTerms[channel] = buildList {
|
||||
if (fit.read > 0.0) add("read")
|
||||
if (fit.shot > 0.0) add("shot")
|
||||
if (fit.quadratic > 0.0) add("quadratic")
|
||||
}.joinToString("+").ifEmpty { "zero" }
|
||||
relativeFitError[channel] = samples.maxOf { sample ->
|
||||
val measured = sample.normalizedYuvVariance[channel].toDouble()
|
||||
val signal = sample.workingLumaMean.toDouble()
|
||||
val predicted = fit.read + fit.shot * signal + fit.quadratic * signal * signal
|
||||
(abs(predicted - measured) / measured.coerceAtLeast(1e-12)).toFloat()
|
||||
}
|
||||
}
|
||||
|
||||
val chromaEnvelopeSignals = DoubleArray(samples.size * 2) { signals[it / 2] }
|
||||
val chromaRequiredSignalVariance = DoubleArray(samples.size * 2) { index ->
|
||||
val sampleIndex = index / 2
|
||||
val channel = 1 + index % 2
|
||||
(samples[sampleIndex].normalizedYuvVariance[channel] - fittedRead[channel])
|
||||
.toDouble()
|
||||
.coerceAtLeast(0.0)
|
||||
}
|
||||
val sharedChromaFit = fitNonUnderestimatingSignalNoisePolynomial(
|
||||
chromaEnvelopeSignals,
|
||||
chromaRequiredSignalVariance,
|
||||
) ?: return null
|
||||
|
||||
val normalizedRead = FloatArray(3) { fittedRead[it] * 4f }
|
||||
val normalizedLumaShot = fittedShot[0] * 2f
|
||||
val normalizedLumaQuadratic = fittedQuadratic[0]
|
||||
val normalizedChromaShot = (sharedChromaFit.shot * 2.0).toFloat()
|
||||
val normalizedChromaQuadratic = sharedChromaFit.quadratic.toFloat()
|
||||
if (normalizedRead.any { !it.isFinite() || it < 0f } ||
|
||||
!normalizedLumaShot.isFinite() || normalizedLumaShot < 0f ||
|
||||
!normalizedLumaQuadratic.isFinite() || normalizedLumaQuadratic < 0f ||
|
||||
!normalizedChromaShot.isFinite() || normalizedChromaShot < 0f ||
|
||||
!normalizedChromaQuadratic.isFinite() || normalizedChromaQuadratic < 0f
|
||||
) {
|
||||
return null
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Demosaic YUV noise model complete " +
|
||||
"signals=${samples.map(NoiseSample::workingLumaMean)} " +
|
||||
"variance=${samples.map { it.normalizedYuvVariance.contentToString() }} " +
|
||||
"readOnlySignal=${readSample.workingLumaMean} " +
|
||||
"readOnlyVariance=${readSample.normalizedYuvVariance.contentToString()} " +
|
||||
"fitTerms=${fitTerms.contentToString()} " +
|
||||
"fitRead=${fittedRead.contentToString()} " +
|
||||
"fitShot=${fittedShot.contentToString()} " +
|
||||
"fitQuadratic=${fittedQuadratic.contentToString()} " +
|
||||
"fitMaxRelativeError=${relativeFitError.contentToString()} " +
|
||||
"sharedChromaShot=${sharedChromaFit.shot} " +
|
||||
"sharedChromaQuadratic=${sharedChromaFit.quadratic} " +
|
||||
"scale2Read=${normalizedRead.contentToString()} " +
|
||||
"scale2LumaShot=$normalizedLumaShot " +
|
||||
"scale2LumaQuadratic=$normalizedLumaQuadratic " +
|
||||
"scale2ChromaShot=$normalizedChromaShot " +
|
||||
"scale2ChromaQuadratic=$normalizedChromaQuadratic",
|
||||
)
|
||||
return DemosaicNoiseTransfer(
|
||||
normalizedRead = normalizedRead,
|
||||
normalizedLumaShot = normalizedLumaShot,
|
||||
normalizedLumaQuadratic = normalizedLumaQuadratic,
|
||||
normalizedChromaShot = normalizedChromaShot,
|
||||
normalizedChromaQuadratic = normalizedChromaQuadratic,
|
||||
lumaCorrelation = lumaCorrelation,
|
||||
chromaCorrelation = chromaCorrelation,
|
||||
)
|
||||
}
|
||||
|
||||
private fun checkGlError(operation: String) {
|
||||
val error = GLES30.glGetError()
|
||||
check(error == GLES30.GL_NO_ERROR) {
|
||||
"Demosaic noise calibration $operation failed with GL error 0x${error.toString(16)}"
|
||||
}
|
||||
}
|
||||
|
||||
private fun pipelineLabel(cfaPattern: Int): String =
|
||||
if (RawMetadata.isQuadBayer(cfaPattern)) "QUAD_BAYER" else "STANDARD_BAYER_VGN"
|
||||
|
||||
private fun elapsedMs(startNs: Long): Long =
|
||||
(System.nanoTime() - startNs) / 1_000_000L
|
||||
|
||||
private companion object {
|
||||
private const val TAG = "DemosaicNoiseCalibrator"
|
||||
private const val CALIBRATION_SIZE = 256
|
||||
private const val ATLAS_HEIGHT = CALIBRATION_SIZE
|
||||
private const val ANALYSIS_SIZE = 128
|
||||
private const val ANALYSIS_ORIGIN = (CALIBRATION_SIZE - ANALYSIS_SIZE) / 2
|
||||
private const val ANALYSIS_PIXELS = ANALYSIS_SIZE * ANALYSIS_SIZE
|
||||
private const val SPECTRUM_BINS = 128
|
||||
private const val REFERENCE_SIGNAL = 0.18f
|
||||
private val SAMPLE_SPECS = arrayOf(
|
||||
NoiseSampleSpec(0.04f, NoiseComponent.TOTAL, includeCorrelation = false),
|
||||
NoiseSampleSpec(REFERENCE_SIGNAL, NoiseComponent.TOTAL, includeCorrelation = true),
|
||||
NoiseSampleSpec(0.50f, NoiseComponent.TOTAL, includeCorrelation = false),
|
||||
NoiseSampleSpec(REFERENCE_SIGNAL, NoiseComponent.READ_ONLY, includeCorrelation = false),
|
||||
)
|
||||
private val REFERENCE_SIGNALS =
|
||||
FloatArray(SAMPLE_SPECS.size) { SAMPLE_SPECS[it].referenceSignal }
|
||||
private val READ_ONLY_SLOT =
|
||||
SAMPLE_SPECS.indexOfFirst { it.component == NoiseComponent.READ_ONLY }
|
||||
private val ATLAS_WIDTH = CALIBRATION_SIZE * SAMPLE_SPECS.size
|
||||
|
||||
// Must remain bit-exact with mgc_full_resolution_denoise_jni.cpp.
|
||||
private val RGB_TO_YUV = floatArrayOf(
|
||||
0.2125999927520752f,
|
||||
0.7152000069618225f,
|
||||
0.07219959795475006f,
|
||||
-0.16245023906230927f,
|
||||
-0.5464943051338196f,
|
||||
0.7089447379112244f,
|
||||
0.9999967217445374f,
|
||||
-0.9083024859428406f,
|
||||
-0.09169333428144455f,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,692 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.processor.DenoiseStrength
|
||||
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
|
||||
import com.hinnka.mycamera.processor.GlesGpuScheduler
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.pow
|
||||
|
||||
/**
|
||||
* OpenGL ES 3.1 compute port of darktable's denoiseprofile NLM path.
|
||||
*
|
||||
* Input and output stay in un-white-balanced camera RGB. The host keeps darktable's
|
||||
* white-balance-adaptive exponent, but removes WB from the reversible signal scale.
|
||||
* The pipeline mirrors darktable process_nlmeans_cl with a mobile fused accumulator and a
|
||||
* low-frequency green guide used to keep low-contrast structure out of the noise estimate:
|
||||
* precondition_v2 -> init -> repeated local-tile accu -> finish_v2.
|
||||
*/
|
||||
object DenoiseProfileShaders {
|
||||
const val SEARCH_RADIUS = 5
|
||||
const val PATCH_RADIUS = 1
|
||||
// darktable's neutral bias setting makes finish_v2 the exact inverse when NLM leaves a
|
||||
// transformed sample unchanged. This is required to keep sensor black and channel ratios.
|
||||
const val BLACK_PRESERVING_BIAS = 0.0f
|
||||
const val IMAGE_LOCAL_X = GlesComputeWorkGroup.IMAGE_TILE_SIZE
|
||||
const val IMAGE_LOCAL_Y = GlesComputeWorkGroup.IMAGE_TILE_SIZE
|
||||
private const val FUSED_TILE_X = IMAGE_LOCAL_X + SEARCH_RADIUS + 2 * PATCH_RADIUS
|
||||
private const val FUSED_TILE_Y = IMAGE_LOCAL_Y + SEARCH_RADIUS + 2 * PATCH_RADIUS
|
||||
|
||||
private const val COMMON = """
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
vec4 readPixel(sampler2D image, ivec2 coord, ivec2 size) {
|
||||
ivec2 c = clamp(coord, ivec2(0), size - ivec2(1));
|
||||
return texelFetch(image, c, 0);
|
||||
}
|
||||
|
||||
vec4 dtPow(vec4 a, vec4 b) {
|
||||
return pow(a, b);
|
||||
}
|
||||
|
||||
float fastMexp2(float x) {
|
||||
const float i1 = float(0x3f800000u);
|
||||
const float i2 = float(0x3f000000u);
|
||||
float k0 = i1 + x * (i2 - i1);
|
||||
uint bits = (k0 >= float(0x800000u)) ? uint(k0) : 0u;
|
||||
return uintBitsToFloat(bits);
|
||||
}
|
||||
|
||||
float ddirac(ivec2 q) {
|
||||
return (q.x != 0 || q.y != 0) ? 1.0 : 0.0;
|
||||
}
|
||||
|
||||
int pixelIndex(ivec2 coord, ivec2 size) {
|
||||
return coord.y * size.x + coord.x;
|
||||
}
|
||||
"""
|
||||
|
||||
val PRECONDITION_V2 = """
|
||||
#version 310 es
|
||||
$COMMON
|
||||
layout(local_size_x = $IMAGE_LOCAL_X, local_size_y = $IMAGE_LOCAL_Y) in;
|
||||
layout(binding = 0) uniform highp sampler2D uInput;
|
||||
layout(rgba16f, binding = 1) writeonly uniform highp image2D uOutput;
|
||||
|
||||
uniform ivec2 uImageSize;
|
||||
uniform vec4 uA;
|
||||
uniform vec4 uP;
|
||||
uniform vec4 uB;
|
||||
uniform vec4 uSignalScale;
|
||||
|
||||
vec4 preconditionSignal(vec4 pixel) {
|
||||
return max(
|
||||
2.0 * dtPow(max(vec4(0.0), pixel / uSignalScale + uB), 1.0 - uP / 2.0) /
|
||||
((-uP + 2.0) * sqrt(uA)),
|
||||
vec4(0.0)
|
||||
);
|
||||
}
|
||||
|
||||
float preconditionGreen(float signal) {
|
||||
return max(
|
||||
2.0 * pow(max(0.0, signal / uSignalScale.g + uB.g), 1.0 - uP.g / 2.0) /
|
||||
((-uP.g + 2.0) * sqrt(uA.g)),
|
||||
0.0
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (coord.x >= uImageSize.x || coord.y >= uImageSize.y) return;
|
||||
|
||||
vec4 t = preconditionSignal(readPixel(uInput, coord, uImageSize));
|
||||
|
||||
// Alpha is scratch space after preconditioning: FUSED_ACCU replaces it with the
|
||||
// accumulated weight and FINISH_V2 restores alpha from the original input. A 3x3
|
||||
// Gaussian green guide expands the effective structural support of the 3x3 RGB
|
||||
// patch without another full-resolution intermediate texture.
|
||||
float guide =
|
||||
preconditionGreen(readPixel(uInput, coord + ivec2(-1, -1), uImageSize).g) +
|
||||
2.0 * preconditionGreen(readPixel(uInput, coord + ivec2(0, -1), uImageSize).g) +
|
||||
preconditionGreen(readPixel(uInput, coord + ivec2(1, -1), uImageSize).g) +
|
||||
2.0 * preconditionGreen(readPixel(uInput, coord + ivec2(-1, 0), uImageSize).g) +
|
||||
4.0 * t.g +
|
||||
2.0 * preconditionGreen(readPixel(uInput, coord + ivec2(1, 0), uImageSize).g) +
|
||||
preconditionGreen(readPixel(uInput, coord + ivec2(-1, 1), uImageSize).g) +
|
||||
2.0 * preconditionGreen(readPixel(uInput, coord + ivec2(0, 1), uImageSize).g) +
|
||||
preconditionGreen(readPixel(uInput, coord + ivec2(1, 1), uImageSize).g);
|
||||
t.a = guide * (1.0 / 16.0);
|
||||
imageStore(uOutput, coord, t);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val INIT = """
|
||||
#version 310 es
|
||||
$COMMON
|
||||
layout(local_size_x = $IMAGE_LOCAL_X, local_size_y = $IMAGE_LOCAL_Y) in;
|
||||
layout(std430, binding = 0) buffer AccuBuffer { vec4 u2[]; };
|
||||
|
||||
uniform ivec2 uImageSize;
|
||||
uniform int uStripeRowCount;
|
||||
|
||||
void main() {
|
||||
ivec2 stripeCoord = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (stripeCoord.x >= uImageSize.x || stripeCoord.y >= uStripeRowCount) return;
|
||||
|
||||
u2[stripeCoord.y * uImageSize.x + stripeCoord.x] = vec4(0.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val FUSED_ACCU = """
|
||||
#version 310 es
|
||||
$COMMON
|
||||
layout(local_size_x = $IMAGE_LOCAL_X, local_size_y = $IMAGE_LOCAL_Y) in;
|
||||
layout(binding = 0) uniform highp sampler2D uInput;
|
||||
layout(std430, binding = 0) buffer AccuBuffer { vec4 u2[]; };
|
||||
|
||||
shared vec2 sDistance[$FUSED_TILE_X * $FUSED_TILE_Y];
|
||||
|
||||
uniform ivec2 uImageSize;
|
||||
uniform int uStripeRowOffset;
|
||||
uniform int uStripeRowCount;
|
||||
uniform ivec2 uQ;
|
||||
uniform float uExpectedFineDistance;
|
||||
uniform float uExpectedGuideDistance;
|
||||
uniform float uInverseBandwidth;
|
||||
uniform float uCoarseGuideWeight;
|
||||
uniform float uCentralPixelWeight;
|
||||
|
||||
vec2 pixelDistance(ivec2 coord, ivec2 q) {
|
||||
ivec2 shifted = coord + q;
|
||||
bool inBounds = shifted.x >= 0 && shifted.x < uImageSize.x &&
|
||||
shifted.y >= 0 && shifted.y < uImageSize.y;
|
||||
if (!inBounds) return vec2(0.0);
|
||||
|
||||
vec4 p1 = readPixel(uInput, coord, uImageSize);
|
||||
vec4 p2 = readPixel(uInput, shifted, uImageSize);
|
||||
vec4 tmp = (p1 - p2) * (p1 - p2);
|
||||
return vec2(tmp.x + tmp.y + tmp.z, tmp.a);
|
||||
}
|
||||
|
||||
vec2 tileDistance(ivec2 imageCoord, ivec2 groupOrigin, ivec2 tileMin, int tileWidth) {
|
||||
ivec2 tileCoord = imageCoord - groupOrigin - tileMin;
|
||||
return sDistance[tileCoord.y * tileWidth + tileCoord.x];
|
||||
}
|
||||
|
||||
float patchWeight(ivec2 center, ivec2 groupOrigin, ivec2 tileMin, int tileWidth) {
|
||||
vec2 distacc = vec2(0.0);
|
||||
for (int pj = -$PATCH_RADIUS; pj <= $PATCH_RADIUS; pj++) {
|
||||
for (int pi = -$PATCH_RADIUS; pi <= $PATCH_RADIUS; pi++) {
|
||||
ivec2 patchCoord = clamp(
|
||||
center + ivec2(pi, pj),
|
||||
ivec2(0),
|
||||
uImageSize - ivec2(1)
|
||||
);
|
||||
distacc += tileDistance(patchCoord, groupOrigin, tileMin, tileWidth);
|
||||
}
|
||||
}
|
||||
|
||||
float patchPixels = float((2 * $PATCH_RADIUS + 1) * (2 * $PATCH_RADIUS + 1));
|
||||
distacc += tileDistance(center, groupOrigin, tileMin, tileWidth) *
|
||||
patchPixels * uCentralPixelWeight;
|
||||
distacc /= 1.0 + uCentralPixelWeight;
|
||||
|
||||
float unexplainedFine = max(distacc.x - uExpectedFineDistance, 0.0);
|
||||
float unexplainedGuide = max(distacc.y - uExpectedGuideDistance, 0.0);
|
||||
float unexplainedDistance =
|
||||
unexplainedFine + uCoarseGuideWeight * unexplainedGuide;
|
||||
return fastMexp2(unexplainedDistance * uInverseBandwidth);
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 groupOrigin = ivec2(
|
||||
int(gl_WorkGroupID.x) * $IMAGE_LOCAL_X,
|
||||
uStripeRowOffset + int(gl_WorkGroupID.y) * $IMAGE_LOCAL_Y
|
||||
);
|
||||
ivec2 tileMin = min(ivec2(-$PATCH_RADIUS), -uQ - ivec2($PATCH_RADIUS));
|
||||
ivec2 tileMax = max(ivec2($PATCH_RADIUS), -uQ + ivec2($PATCH_RADIUS));
|
||||
int tileWidth = $IMAGE_LOCAL_X + tileMax.x - tileMin.x;
|
||||
int tileHeight = $IMAGE_LOCAL_Y + tileMax.y - tileMin.y;
|
||||
int tilePixels = tileWidth * tileHeight;
|
||||
int localIndex = int(gl_LocalInvocationID.y) * $IMAGE_LOCAL_X +
|
||||
int(gl_LocalInvocationID.x);
|
||||
int localCount = $IMAGE_LOCAL_X * $IMAGE_LOCAL_Y;
|
||||
|
||||
for (int i = localIndex; i < tilePixels; i += localCount) {
|
||||
int tileX = i - (i / tileWidth) * tileWidth;
|
||||
int tileY = i / tileWidth;
|
||||
ivec2 imageCoord = groupOrigin + ivec2(tileX, tileY) + tileMin;
|
||||
imageCoord = clamp(imageCoord, ivec2(0), uImageSize - ivec2(1));
|
||||
sDistance[i] = pixelDistance(imageCoord, uQ);
|
||||
}
|
||||
|
||||
memoryBarrierShared();
|
||||
barrier();
|
||||
|
||||
ivec2 stripeCoord = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (stripeCoord.x >= uImageSize.x || stripeCoord.y >= uStripeRowCount) return;
|
||||
ivec2 coord = stripeCoord + ivec2(0, uStripeRowOffset);
|
||||
|
||||
ivec2 plusCoord = coord + uQ;
|
||||
ivec2 minusCoord = coord - uQ;
|
||||
bool plusInBounds = plusCoord.x >= 0 && plusCoord.x < uImageSize.x &&
|
||||
plusCoord.y >= 0 && plusCoord.y < uImageSize.y;
|
||||
bool minusInBounds = minusCoord.x >= 0 && minusCoord.x < uImageSize.x &&
|
||||
minusCoord.y >= 0 && minusCoord.y < uImageSize.y;
|
||||
|
||||
float weight = plusInBounds ? patchWeight(coord, groupOrigin, tileMin, tileWidth) : 0.0;
|
||||
float weightMinus = (minusInBounds && ddirac(uQ) > 0.0)
|
||||
? patchWeight(minusCoord, groupOrigin, tileMin, tileWidth)
|
||||
: 0.0;
|
||||
|
||||
vec4 u1Pq = plusInBounds ? readPixel(uInput, plusCoord, uImageSize) : vec4(0.0);
|
||||
vec4 u1Mq = minusInBounds ? readPixel(uInput, minusCoord, uImageSize) : vec4(0.0);
|
||||
vec4 accu = weight * u1Pq + weightMinus * u1Mq;
|
||||
accu.a = weight + weightMinus;
|
||||
|
||||
int idx = stripeCoord.y * uImageSize.x + stripeCoord.x;
|
||||
u2[idx] = u2[idx] + accu;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val FINISH_V2 = """
|
||||
#version 310 es
|
||||
$COMMON
|
||||
layout(local_size_x = $IMAGE_LOCAL_X, local_size_y = $IMAGE_LOCAL_Y) in;
|
||||
layout(binding = 0) uniform highp sampler2D uInput;
|
||||
layout(std430, binding = 0) readonly buffer AccuBuffer { vec4 u2[]; };
|
||||
layout(rgba16f, binding = 1) writeonly uniform highp image2D uOutput;
|
||||
|
||||
uniform ivec2 uImageSize;
|
||||
uniform int uStripeRowOffset;
|
||||
uniform int uStripeRowCount;
|
||||
uniform vec4 uA;
|
||||
uniform vec4 uP;
|
||||
uniform vec4 uB;
|
||||
uniform float uBias;
|
||||
uniform float uDenoiseMix;
|
||||
uniform vec4 uSignalScale;
|
||||
|
||||
void main() {
|
||||
ivec2 stripeCoord = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (stripeCoord.x >= uImageSize.x || stripeCoord.y >= uStripeRowCount) return;
|
||||
ivec2 coord = stripeCoord + ivec2(0, uStripeRowOffset);
|
||||
|
||||
int idx = stripeCoord.y * uImageSize.x + stripeCoord.x;
|
||||
vec4 accu = u2[idx];
|
||||
vec4 original = readPixel(uInput, coord, uImageSize);
|
||||
vec4 px = accu.a > 0.0 ? accu / accu.a : vec4(0.0);
|
||||
|
||||
vec4 delta = px * px + vec4(uBias);
|
||||
vec4 denominator = 4.0 / (sqrt(uA) * (2.0 - uP));
|
||||
vec4 z1 = (px + sqrt(max(vec4(0.0), delta))) / denominator;
|
||||
px = max(dtPow(z1, 1.0 / (1.0 - uP / 2.0)) - uB, vec4(0.0));
|
||||
px *= uSignalScale;
|
||||
px.rgb = mix(original.rgb, px.rgb, clamp(uDenoiseMix, 0.0, 1.0));
|
||||
px.a = original.a;
|
||||
imageStore(uOutput, coord, px);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
|
||||
/** Complete darktable denoiseprofile variance-transform + striped NLM algorithm. */
|
||||
internal class DenoiseProfileAlgorithm {
|
||||
data class Input(
|
||||
val sourceTextureId: Int,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val strength: Float,
|
||||
val noiseSlope: Float,
|
||||
val noiseOffset: Float,
|
||||
val adaptiveWhiteBalance: FloatArray,
|
||||
)
|
||||
|
||||
data class Output(val textureId: Int, val width: Int, val height: Int)
|
||||
|
||||
private data class Params(
|
||||
val strength: Float,
|
||||
val bias: Float,
|
||||
val scale: Float,
|
||||
val expectedFineDistance: Float,
|
||||
val expectedGuideDistance: Float,
|
||||
val inverseBandwidth: Float,
|
||||
val coarseGuideWeight: Float,
|
||||
val centralPixelWeight: Float,
|
||||
val p: FloatArray,
|
||||
val signalScale: FloatArray,
|
||||
val aa: FloatArray,
|
||||
val bb: FloatArray,
|
||||
)
|
||||
|
||||
private var preconditionProgram = 0
|
||||
private var initProgram = 0
|
||||
private var fusedAccumulateProgram = 0
|
||||
private var finishProgram = 0
|
||||
private val textureIds = intArrayOf(0, 0)
|
||||
private var textureWidth = 0
|
||||
private var textureHeight = 0
|
||||
private var accumulatorBufferId = 0
|
||||
private var accumulatorWidth = 0
|
||||
private var accumulatorRows = 0
|
||||
private var maxSsboBytes = 0L
|
||||
|
||||
fun initialize(): Boolean {
|
||||
if (preconditionProgram == 0) {
|
||||
preconditionProgram = RawGlesProgram.compileCompute(
|
||||
DenoiseProfileShaders.PRECONDITION_V2,
|
||||
"DENOISE_PROFILE_PRECONDITION",
|
||||
)
|
||||
}
|
||||
if (initProgram == 0) {
|
||||
initProgram = RawGlesProgram.compileCompute(
|
||||
DenoiseProfileShaders.INIT,
|
||||
"DENOISE_PROFILE_INIT",
|
||||
)
|
||||
}
|
||||
if (fusedAccumulateProgram == 0) {
|
||||
fusedAccumulateProgram = RawGlesProgram.compileCompute(
|
||||
DenoiseProfileShaders.FUSED_ACCU,
|
||||
"DENOISE_PROFILE_FUSED_ACCU",
|
||||
)
|
||||
}
|
||||
if (finishProgram == 0) {
|
||||
finishProgram = RawGlesProgram.compileCompute(
|
||||
DenoiseProfileShaders.FINISH_V2,
|
||||
"DENOISE_PROFILE_FINISH",
|
||||
)
|
||||
}
|
||||
return programsReady()
|
||||
}
|
||||
|
||||
fun execute(input: Input): Output? {
|
||||
if (input.strength <= 0f || input.width * input.height < 2) {
|
||||
return Output(input.sourceTextureId, input.width, input.height)
|
||||
}
|
||||
require(input.adaptiveWhiteBalance.size >= 3)
|
||||
if (!initialize() || !ensureResources(input.width, input.height)) return null
|
||||
val params = buildParams(input)
|
||||
PLog.d(
|
||||
TAG,
|
||||
"execute: size=${input.width}x${input.height} strength=${params.strength} " +
|
||||
"slope=${input.noiseSlope} offset=${input.noiseOffset} " +
|
||||
"stripeRows=$accumulatorRows wb=${input.adaptiveWhiteBalance.contentToString()}",
|
||||
)
|
||||
dispatchPrecondition(input, params)
|
||||
dispatchNlm(input, params)
|
||||
RawGlesProgram.logErrors("DenoiseProfile execute")
|
||||
return Output(textureIds[1], input.width, input.height)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
intArrayOf(
|
||||
preconditionProgram,
|
||||
initProgram,
|
||||
fusedAccumulateProgram,
|
||||
finishProgram,
|
||||
).forEach { program ->
|
||||
if (program != 0) GLES31.glDeleteProgram(program)
|
||||
}
|
||||
preconditionProgram = 0
|
||||
initProgram = 0
|
||||
fusedAccumulateProgram = 0
|
||||
finishProgram = 0
|
||||
releaseTextures()
|
||||
releaseAccumulator()
|
||||
maxSsboBytes = 0L
|
||||
}
|
||||
|
||||
private fun programsReady(): Boolean =
|
||||
preconditionProgram != 0 && initProgram != 0 &&
|
||||
fusedAccumulateProgram != 0 && finishProgram != 0
|
||||
|
||||
private fun ensureResources(width: Int, height: Int): Boolean {
|
||||
if (textureWidth != width || textureHeight != height || textureIds.any { it == 0 }) {
|
||||
releaseTextures()
|
||||
GLES30.glGenTextures(textureIds.size, textureIds, 0)
|
||||
textureIds.forEach { textureId ->
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
|
||||
GLES30.glTexStorage2D(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
1,
|
||||
GLES30.GL_RGBA16F,
|
||||
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,
|
||||
)
|
||||
GLES30.glTexParameteri(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
GLES30.GL_TEXTURE_WRAP_S,
|
||||
GLES30.GL_CLAMP_TO_EDGE,
|
||||
)
|
||||
GLES30.glTexParameteri(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
GLES30.GL_TEXTURE_WRAP_T,
|
||||
GLES30.GL_CLAMP_TO_EDGE,
|
||||
)
|
||||
}
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
textureWidth = width
|
||||
textureHeight = height
|
||||
}
|
||||
ensureAccumulator(width, height)
|
||||
RawGlesProgram.logErrors("DenoiseProfile resources")
|
||||
return textureIds.all { it != 0 } && accumulatorBufferId != 0 && accumulatorRows > 0
|
||||
}
|
||||
|
||||
private fun ensureAccumulator(width: Int, height: Int) {
|
||||
if (accumulatorWidth == width && accumulatorRows > 0 && accumulatorBufferId != 0) return
|
||||
releaseAccumulator()
|
||||
var rows = DenoiseProfileStripePlanner.capacityRows(width, height, queryMaxSsboBytes())
|
||||
if (rows <= 0) return
|
||||
val buffers = IntArray(1)
|
||||
GLES31.glGenBuffers(1, buffers, 0)
|
||||
accumulatorBufferId = buffers[0]
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, accumulatorBufferId)
|
||||
while (rows > 0) {
|
||||
val bytes = DenoiseProfileStripePlanner.requiredBytes(width, rows)
|
||||
GLES31.glBufferData(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
bytes.toInt(),
|
||||
null,
|
||||
GLES31.GL_DYNAMIC_DRAW,
|
||||
)
|
||||
val error = GLES30.glGetError()
|
||||
if (error == GLES30.GL_NO_ERROR) {
|
||||
accumulatorWidth = width
|
||||
accumulatorRows = rows
|
||||
break
|
||||
}
|
||||
PLog.w(TAG, "accumulator ${width}x$rows allocation failed: glError=$error")
|
||||
rows = nextSmallerStripeRows(rows)
|
||||
}
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
|
||||
if (accumulatorRows == 0) releaseAccumulator()
|
||||
}
|
||||
|
||||
private fun queryMaxSsboBytes(): Long {
|
||||
if (maxSsboBytes > 0L) return maxSsboBytes
|
||||
val value = LongArray(1)
|
||||
GLES30.glGetInteger64v(GLES31.GL_MAX_SHADER_STORAGE_BLOCK_SIZE, value, 0)
|
||||
val error = GLES30.glGetError()
|
||||
maxSsboBytes = if (error == GLES30.GL_NO_ERROR && value[0] > 0L) {
|
||||
value[0]
|
||||
} else {
|
||||
PLog.w(TAG, "GL_MAX_SHADER_STORAGE_BLOCK_SIZE unavailable; using GLES minimum")
|
||||
GLES31_MIN_SSBO_BYTES
|
||||
}
|
||||
return maxSsboBytes
|
||||
}
|
||||
|
||||
private fun nextSmallerStripeRows(currentRows: Int): Int {
|
||||
if (currentRows <= 1) return 0
|
||||
val half = currentRows / 2
|
||||
val workgroupRows = DenoiseProfileShaders.IMAGE_LOCAL_Y
|
||||
return if (half >= workgroupRows) half - half % workgroupRows else half
|
||||
}
|
||||
|
||||
private fun buildParams(input: Input): Params {
|
||||
val strength = DenoiseStrength.clamp(input.strength)
|
||||
val varianceScale = DenoiseStrength.noiseVarianceScale(strength)
|
||||
val a = (input.noiseSlope * varianceScale).coerceAtLeast(1e-10f)
|
||||
val b = (input.noiseOffset * varianceScale).coerceAtLeast(1e-10f)
|
||||
val scale = 1f
|
||||
val shadows = max(0.1f - 0.1f * ln(a), 0.7f).coerceAtMost(1.8f)
|
||||
val p = FloatArray(4) { index ->
|
||||
if (index == 3) 1f else {
|
||||
max(shadows + 0.1f * ln(scale / input.adaptiveWhiteBalance[index]), 0f)
|
||||
}
|
||||
}
|
||||
val compensateP = 0.05f / 0.05f.pow(shadows)
|
||||
val tuning = DenoiseProfileNlmConfig.weightTuning(DenoiseProfileShaders.PATCH_RADIUS)
|
||||
return Params(
|
||||
strength = strength,
|
||||
bias = DenoiseProfileShaders.BLACK_PRESERVING_BIAS,
|
||||
scale = scale,
|
||||
expectedFineDistance = tuning.expectedFineDistance,
|
||||
expectedGuideDistance = tuning.expectedGuideDistance,
|
||||
inverseBandwidth = tuning.inverseBandwidth,
|
||||
coarseGuideWeight = tuning.coarseGuideWeight,
|
||||
centralPixelWeight = 0.1f * scale,
|
||||
p = p,
|
||||
signalScale = floatArrayOf(scale, scale, scale, 1f),
|
||||
aa = floatArrayOf(a * compensateP, a * compensateP, a * compensateP, 1f),
|
||||
bb = floatArrayOf(b, b, b, 1f),
|
||||
)
|
||||
}
|
||||
|
||||
private fun dispatchPrecondition(input: Input, params: Params) {
|
||||
GLES31.glUseProgram(preconditionProgram)
|
||||
bindSampler(preconditionProgram, "uInput", 0, input.sourceTextureId)
|
||||
GLES31.glBindImageTexture(
|
||||
1,
|
||||
textureIds[0],
|
||||
0,
|
||||
false,
|
||||
0,
|
||||
GLES31.GL_WRITE_ONLY,
|
||||
GLES30.GL_RGBA16F,
|
||||
)
|
||||
setCommonUniforms(preconditionProgram, input.width, input.height, params)
|
||||
dispatchImage(input.width, input.height, "precondition")
|
||||
}
|
||||
|
||||
private fun dispatchNlm(input: Input, params: Params) {
|
||||
DenoiseProfileStripePlanner.plan(input.height, accumulatorRows).forEach { stripe ->
|
||||
dispatchInit(input.width, input.height, stripe)
|
||||
DenoiseProfileNlmConfig.searchOffsets.forEach { offset ->
|
||||
dispatchAccumulate(input.width, input.height, stripe, offset.x, offset.y, params)
|
||||
}
|
||||
dispatchFinish(input, stripe, params)
|
||||
GlesGpuScheduler.yieldToUiRenderer()
|
||||
}
|
||||
}
|
||||
|
||||
private fun dispatchInit(width: Int, height: Int, stripe: DenoiseProfileStripe) {
|
||||
GLES31.glUseProgram(initProgram)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, accumulatorBufferId)
|
||||
GLES31.glUniform2i(GLES31.glGetUniformLocation(initProgram, "uImageSize"), width, height)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(initProgram, "uStripeRowCount"),
|
||||
stripe.rowCount,
|
||||
)
|
||||
dispatchImage(width, stripe.rowCount, "init row=${stripe.rowOffset}")
|
||||
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
|
||||
}
|
||||
|
||||
private fun dispatchAccumulate(
|
||||
width: Int,
|
||||
height: Int,
|
||||
stripe: DenoiseProfileStripe,
|
||||
qx: Int,
|
||||
qy: Int,
|
||||
params: Params,
|
||||
) {
|
||||
GLES31.glUseProgram(fusedAccumulateProgram)
|
||||
bindSampler(fusedAccumulateProgram, "uInput", 0, textureIds[0])
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, accumulatorBufferId)
|
||||
GLES31.glUniform2i(
|
||||
GLES31.glGetUniformLocation(fusedAccumulateProgram, "uImageSize"),
|
||||
width,
|
||||
height,
|
||||
)
|
||||
setStripeUniforms(fusedAccumulateProgram, stripe)
|
||||
GLES31.glUniform2i(GLES31.glGetUniformLocation(fusedAccumulateProgram, "uQ"), qx, qy)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(fusedAccumulateProgram, "uExpectedFineDistance"),
|
||||
params.expectedFineDistance,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(fusedAccumulateProgram, "uExpectedGuideDistance"),
|
||||
params.expectedGuideDistance,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(fusedAccumulateProgram, "uInverseBandwidth"),
|
||||
params.inverseBandwidth,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(fusedAccumulateProgram, "uCoarseGuideWeight"),
|
||||
params.coarseGuideWeight,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(fusedAccumulateProgram, "uCentralPixelWeight"),
|
||||
params.centralPixelWeight,
|
||||
)
|
||||
dispatchImage(width, stripe.rowCount, "accumulate row=${stripe.rowOffset} q=($qx,$qy)")
|
||||
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
|
||||
}
|
||||
|
||||
private fun dispatchFinish(input: Input, stripe: DenoiseProfileStripe, params: Params) {
|
||||
GLES31.glUseProgram(finishProgram)
|
||||
bindSampler(finishProgram, "uInput", 0, input.sourceTextureId)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, accumulatorBufferId)
|
||||
GLES31.glBindImageTexture(
|
||||
1,
|
||||
textureIds[1],
|
||||
0,
|
||||
false,
|
||||
0,
|
||||
GLES31.GL_WRITE_ONLY,
|
||||
GLES30.GL_RGBA16F,
|
||||
)
|
||||
setCommonUniforms(finishProgram, input.width, input.height, params)
|
||||
setStripeUniforms(finishProgram, stripe)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(finishProgram, "uBias"),
|
||||
params.bias - 0.5f * ln(params.scale),
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(finishProgram, "uDenoiseMix"),
|
||||
DenoiseStrength.outputMix(params.strength),
|
||||
)
|
||||
dispatchImage(input.width, stripe.rowCount, "finish row=${stripe.rowOffset}")
|
||||
}
|
||||
|
||||
private fun setCommonUniforms(program: Int, width: Int, height: Int, params: Params) {
|
||||
GLES31.glUniform2i(GLES31.glGetUniformLocation(program, "uImageSize"), width, height)
|
||||
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uA"), 1, params.aa, 0)
|
||||
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uP"), 1, params.p, 0)
|
||||
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uB"), 1, params.bb, 0)
|
||||
GLES31.glUniform4fv(
|
||||
GLES31.glGetUniformLocation(program, "uSignalScale"),
|
||||
1,
|
||||
params.signalScale,
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
private fun setStripeUniforms(program: Int, stripe: DenoiseProfileStripe) {
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(program, "uStripeRowOffset"),
|
||||
stripe.rowOffset,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(program, "uStripeRowCount"),
|
||||
stripe.rowCount,
|
||||
)
|
||||
}
|
||||
|
||||
private fun bindSampler(program: Int, name: String, unit: Int, textureId: Int) {
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + unit)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, textureId)
|
||||
GLES31.glUniform1i(GLES31.glGetUniformLocation(program, name), unit)
|
||||
}
|
||||
|
||||
private fun dispatchImage(width: Int, height: Int, label: String) {
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount(width),
|
||||
GlesComputeWorkGroup.imageGroupCount(height),
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
|
||||
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
|
||||
)
|
||||
RawGlesProgram.logErrors("$TAG $label")
|
||||
}
|
||||
|
||||
private fun releaseTextures() {
|
||||
val live = textureIds.filter { it != 0 }.toIntArray()
|
||||
if (live.isNotEmpty()) GLES30.glDeleteTextures(live.size, live, 0)
|
||||
textureIds.fill(0)
|
||||
textureWidth = 0
|
||||
textureHeight = 0
|
||||
}
|
||||
|
||||
private fun releaseAccumulator() {
|
||||
if (accumulatorBufferId != 0) {
|
||||
GLES31.glDeleteBuffers(1, intArrayOf(accumulatorBufferId), 0)
|
||||
accumulatorBufferId = 0
|
||||
}
|
||||
accumulatorWidth = 0
|
||||
accumulatorRows = 0
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "DenoiseProfile"
|
||||
const val GLES31_MIN_SSBO_BYTES = 128L * 1024L * 1024L
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import kotlin.math.max
|
||||
|
||||
internal data class DenoiseProfileOffset(
|
||||
val x: Int,
|
||||
val y: Int,
|
||||
)
|
||||
|
||||
internal data class DenoiseProfileWeightTuning(
|
||||
val expectedFineDistance: Float,
|
||||
val expectedGuideDistance: Float,
|
||||
val inverseBandwidth: Float,
|
||||
val coarseGuideWeight: Float,
|
||||
)
|
||||
|
||||
/**
|
||||
* Statistical and traversal configuration shared by the RAW and bitmap NLM hosts.
|
||||
*
|
||||
* The variance-stabilizing transform targets unit noise variance per color channel. The
|
||||
* difference between two independent samples therefore has variance two. Noise-only patch
|
||||
* energy is removed before applying the NLM bandwidth so that the weight curve starts falling
|
||||
* as soon as a candidate contains energy that the sensor noise model cannot explain.
|
||||
*/
|
||||
internal object DenoiseProfileNlmConfig {
|
||||
private const val COLOR_CHANNEL_COUNT = 3
|
||||
private const val DIFFERENCE_VARIANCE = 2.0f
|
||||
|
||||
// Squared-energy of the separable 3x3 Gaussian kernel [1 2 1]^T[1 2 1] / 16.
|
||||
private const val GUIDE_FILTER_ENERGY = 36.0f / 256.0f
|
||||
|
||||
// Coarse guide differences describe structure rather than independent RGB noise. Give them
|
||||
// enough leverage to reject low-contrast contours without turning the decision into a hard
|
||||
// threshold.
|
||||
const val COARSE_GUIDE_WEIGHT = 8.0f
|
||||
|
||||
val searchOffsets: List<DenoiseProfileOffset> = buildSearchOffsets(
|
||||
DenoiseProfileShaders.SEARCH_RADIUS
|
||||
)
|
||||
|
||||
fun buildSearchOffsets(radius: Int): List<DenoiseProfileOffset> {
|
||||
require(radius >= 0) { "radius must be non-negative" }
|
||||
return buildList {
|
||||
for (qy in -radius..0) {
|
||||
// FUSED_ACCU evaluates +q and -q together. At y == 0 only one horizontal
|
||||
// half-axis is needed; visiting both halves would double horizontal weights.
|
||||
val qxEnd = if (qy == 0) 0 else radius
|
||||
for (qx in -radius..qxEnd) {
|
||||
add(DenoiseProfileOffset(qx, qy))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun weightTuning(patchRadius: Int): DenoiseProfileWeightTuning {
|
||||
require(patchRadius >= 0) { "patchRadius must be non-negative" }
|
||||
val patchWidth = 2 * patchRadius + 1
|
||||
val patchPixels = patchWidth * patchWidth
|
||||
val expectedFineDistance =
|
||||
DIFFERENCE_VARIANCE * COLOR_CHANNEL_COUNT * patchPixels.toFloat()
|
||||
val expectedGuideDistance =
|
||||
DIFFERENCE_VARIANCE * GUIDE_FILTER_ENERGY * patchPixels.toFloat()
|
||||
|
||||
return DenoiseProfileWeightTuning(
|
||||
expectedFineDistance = expectedFineDistance,
|
||||
expectedGuideDistance = expectedGuideDistance,
|
||||
// One additional noise-floor worth of unexplained RGB energy halves the weight.
|
||||
inverseBandwidth = 1.0f / max(expectedFineDistance, 1.0f),
|
||||
coarseGuideWeight = COARSE_GUIDE_WEIGHT,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
internal data class DenoiseProfileStripe(
|
||||
val rowOffset: Int,
|
||||
val rowCount: Int,
|
||||
)
|
||||
|
||||
/**
|
||||
* Bounds the NLM accumulator SSBO while keeping input sampling in full-image coordinates.
|
||||
* A vec4 accumulator costs 16 bytes per output pixel.
|
||||
*/
|
||||
internal object DenoiseProfileStripePlanner {
|
||||
const val ACCUMULATOR_BYTES_PER_PIXEL = 16L
|
||||
const val PREFERRED_STRIPE_ROWS = 256
|
||||
const val TARGET_BUFFER_BYTES = 64L * 1024L * 1024L
|
||||
|
||||
fun capacityRows(
|
||||
imageWidth: Int,
|
||||
imageHeight: Int,
|
||||
maxShaderStorageBlockBytes: Long,
|
||||
): Int {
|
||||
if (imageWidth <= 0 || imageHeight <= 0 || maxShaderStorageBlockBytes <= 0L) return 0
|
||||
val rowBytes = imageWidth.toLong() * ACCUMULATOR_BYTES_PER_PIXEL
|
||||
if (rowBytes > maxShaderStorageBlockBytes) return 0
|
||||
|
||||
val byteBudget = minOf(maxShaderStorageBlockBytes, TARGET_BUFFER_BYTES)
|
||||
val rowsByBudget = (byteBudget / rowBytes).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
|
||||
val candidate = minOf(imageHeight, PREFERRED_STRIPE_ROWS, rowsByBudget)
|
||||
val workgroupRows = DenoiseProfileShaders.IMAGE_LOCAL_Y
|
||||
return if (candidate >= workgroupRows) {
|
||||
candidate - candidate % workgroupRows
|
||||
} else {
|
||||
candidate
|
||||
}
|
||||
}
|
||||
|
||||
fun requiredBytes(imageWidth: Int, capacityRows: Int): Long =
|
||||
imageWidth.toLong() * capacityRows.toLong() * ACCUMULATOR_BYTES_PER_PIXEL
|
||||
|
||||
fun plan(imageHeight: Int, capacityRows: Int): List<DenoiseProfileStripe> {
|
||||
require(imageHeight > 0) { "Image height must be positive" }
|
||||
require(capacityRows > 0) { "Stripe capacity must be positive" }
|
||||
return buildList {
|
||||
var rowOffset = 0
|
||||
while (rowOffset < imageHeight) {
|
||||
val rowCount = minOf(capacityRows, imageHeight - rowOffset)
|
||||
add(DenoiseProfileStripe(rowOffset, rowCount))
|
||||
rowOffset += rowCount
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,778 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.content.Context
|
||||
import com.hinnka.mycamera.processor.PhotonSensorSizeTuning
|
||||
import com.hinnka.mycamera.processor.DenoiseStrength
|
||||
import com.hinnka.mycamera.processor.PhotonSabreLumaTuningNodes
|
||||
import com.hinnka.mycamera.processor.RawNoiseModel
|
||||
import com.hinnka.mycamera.processor.RawStackRuntimeDebug
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/**
|
||||
* Host bridge for the non-AI MGC 9.6.080 V24 full-resolution denoise chain.
|
||||
*
|
||||
* RGB→YUV, ChromaDenoisePyramidComplete, Pecan luma, YUV→RGB and
|
||||
* ComputeDenoiseStrengthMaps execute the mechanically lifted static kernels.
|
||||
* The recovered MGC boundary keeps chroma as a sibling stage immediately
|
||||
* before RunFullResolutionDenoise/Pecan.
|
||||
*
|
||||
* This class owns luma/chroma protobuf tuning selection and normalized
|
||||
* noise-model preparation. Spatial consumes its propagated correlation/coefficient/strength
|
||||
* outputs; classic Sabre consumes its dedicated luma tuning and the variance propagated by
|
||||
* MgcSabreMergedNoiseModel from per-frame models and V25's SNR correction. The native bridge
|
||||
* converts normalized read/shot/quadratic coefficients once at the Q14 S16 kernel boundary.
|
||||
*/
|
||||
internal object MgcFullResolutionDenoise {
|
||||
private const val TAG = "MgcFullResolutionDenoise"
|
||||
private const val LUMA_TUNING_ASSET =
|
||||
"mgc_denoise/luma_denoise_default.binarypb"
|
||||
private const val SABRE_LUMA_TUNING_ASSET =
|
||||
"mgc_denoise/sabre_luma_denoise.binarypb"
|
||||
private const val CHROMA_TUNING_ASSET =
|
||||
"mgc_denoise/chroma_denoise.binarypb"
|
||||
|
||||
data class Tuning(
|
||||
val strength: FloatArray,
|
||||
val revertFactor: FloatArray,
|
||||
val outlierDistance: FloatArray,
|
||||
)
|
||||
|
||||
/**
|
||||
* Merge defaults consume their processor-specific model exactly once before DNG write.
|
||||
* User adjustment deliberately ignores Spatial merge diagnostics. When the caller supplies
|
||||
* a measured demosaic model it consumes the propagated spectrum/YUV coefficients and applies
|
||||
* LSC through the identity base-strength map; otherwise it retains the identity fallback.
|
||||
*/
|
||||
enum class Pass {
|
||||
SPATIAL_DEFAULT,
|
||||
SABRE_DEFAULT,
|
||||
USER_ADJUSTMENT,
|
||||
}
|
||||
|
||||
enum class InputLayout {
|
||||
CAMERA_RGBA16F,
|
||||
NORMALIZED_BAYER16,
|
||||
}
|
||||
|
||||
data class NormalizedCameraRgbNoise(
|
||||
val read: FloatArray,
|
||||
val shot: FloatArray,
|
||||
)
|
||||
|
||||
/**
|
||||
* Noise model at MGC's white-balanced Y/Cb/Cr boundary after NoiseModel.Scale(2).
|
||||
*
|
||||
* ChromaDenoisePyramidComplete keeps per-channel read variance, but its generated ABI
|
||||
* accepts only one shared shot/quadratic curve. The measured VGN path stores its fitted
|
||||
* shared chroma curve here; the ordinary MGC NoiseModel path instead reproduces the
|
||||
* original builder's channel-0 slice directly in native code.
|
||||
*/
|
||||
data class PreparedYuvNoiseModel(
|
||||
val normalizedRead: FloatArray,
|
||||
val normalizedLumaShot: Float,
|
||||
val normalizedLumaQuadratic: Float,
|
||||
val normalizedChromaShot: Float,
|
||||
val normalizedChromaQuadratic: Float,
|
||||
val lumaCorrelation: FloatArray,
|
||||
val chromaCorrelation: FloatArray,
|
||||
)
|
||||
|
||||
internal data class TuningPoint(
|
||||
val snr: Float,
|
||||
val tuning: Tuning,
|
||||
)
|
||||
|
||||
@Volatile
|
||||
private var initialized = false
|
||||
@Volatile
|
||||
private var initializationFailed = false
|
||||
private var lumaTuningPoints: List<TuningPoint> = emptyList()
|
||||
private var sabreLumaTuningPoints: List<TuningPoint> = emptyList()
|
||||
private var chromaTuningPoints: List<TuningPoint> = emptyList()
|
||||
|
||||
@Synchronized
|
||||
fun ensureInitialized(context: Context): Boolean {
|
||||
if (initialized) return true
|
||||
if (initializationFailed) return false
|
||||
return runCatching {
|
||||
val assets = context.applicationContext.assets
|
||||
val lumaTuningBytes =
|
||||
assets.open(LUMA_TUNING_ASSET).use { it.readBytes() }
|
||||
val sabreLumaTuningBytes =
|
||||
assets.open(SABRE_LUMA_TUNING_ASSET).use { it.readBytes() }
|
||||
val chromaTuningBytes =
|
||||
assets.open(CHROMA_TUNING_ASSET).use { it.readBytes() }
|
||||
lumaTuningPoints = parseTuning(lumaTuningBytes)
|
||||
sabreLumaTuningPoints = parseTuning(sabreLumaTuningBytes)
|
||||
chromaTuningPoints = parseTuning(chromaTuningBytes)
|
||||
check(lumaTuningPoints.size >= 2) {
|
||||
"MGC luma tuning contains fewer than two SNR points"
|
||||
}
|
||||
check(sabreLumaTuningPoints.size >= 2) {
|
||||
"MGC Sabre luma tuning contains fewer than two SNR points"
|
||||
}
|
||||
check(chromaTuningPoints.size >= 2) {
|
||||
"MGC chroma tuning contains fewer than two SNR points"
|
||||
}
|
||||
initialized = true
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC RunFullResolutionDenoise static kernels ready: " +
|
||||
"lumaSnr=${lumaTuningPoints.map { it.snr }} " +
|
||||
"sabreLumaSnr=${sabreLumaTuningPoints.map { it.snr }} " +
|
||||
"chromaSnr=${chromaTuningPoints.map { it.snr }}",
|
||||
)
|
||||
true
|
||||
}.onFailure { error ->
|
||||
initializationFailed = true
|
||||
PLog.e(TAG, "Unable to initialize MGC RunFullResolutionDenoise", error)
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs MGC RunFullResolutionDenoise in place. CAMERA_RGBA16F is the
|
||||
* existing camera-RGB boundary. NORMALIZED_BAYER16 consumes one unsigned
|
||||
* normalized Bayer plane from the beginning of the buffer and overwrites
|
||||
* it with RGBA16F after MGC's own BayerRawToYuv path.
|
||||
*/
|
||||
fun denoise(
|
||||
rgba16f: ByteBuffer,
|
||||
width: Int,
|
||||
height: Int,
|
||||
globalOriginX: Int,
|
||||
globalOriginY: Int,
|
||||
fullWidth: Int,
|
||||
fullHeight: Int,
|
||||
outputScale: Float = 1f,
|
||||
inputLayout: InputLayout = InputLayout.CAMERA_RGBA16F,
|
||||
applyLensShadingInBayerAot: Boolean = false,
|
||||
metadata: RawMetadata,
|
||||
preparedYuvNoiseModel: PreparedYuvNoiseModel? = null,
|
||||
applyLensShadingToDenoiseStrength: Boolean = false,
|
||||
tuningSnr: Float,
|
||||
pass: Pass,
|
||||
lumaStrengthScale: Float,
|
||||
chromaStrengthScale: Float,
|
||||
): Boolean {
|
||||
val finiteLumaScale = DenoiseStrength.clamp(lumaStrengthScale)
|
||||
val finiteChromaScale = DenoiseStrength.clamp(chromaStrengthScale)
|
||||
val lumaEnabled = finiteLumaScale > 0f
|
||||
val chromaEnabled = finiteChromaScale > 0f
|
||||
if (!initialized || !rgba16f.isDirect || width <= 0 || height <= 0 ||
|
||||
!outputScale.isFinite() || outputScale <= 0f ||
|
||||
(!lumaEnabled && !chromaEnabled)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
val useSpatialModel = pass == Pass.SPATIAL_DEFAULT
|
||||
val useSabreModel = pass == Pass.SABRE_DEFAULT
|
||||
if (preparedYuvNoiseModel != null &&
|
||||
(inputLayout != InputLayout.CAMERA_RGBA16F ||
|
||||
!validPreparedYuvNoise(preparedYuvNoiseModel))
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"MGC denoise rejected malformed prepared VGN YUV model: " +
|
||||
"read=${preparedYuvNoiseModel.normalizedRead.contentToString()} " +
|
||||
"lumaShot=${preparedYuvNoiseModel.normalizedLumaShot} " +
|
||||
"lumaQuadratic=${preparedYuvNoiseModel.normalizedLumaQuadratic} " +
|
||||
"chromaShot=${preparedYuvNoiseModel.normalizedChromaShot} " +
|
||||
"chromaQuadratic=${preparedYuvNoiseModel.normalizedChromaQuadratic}",
|
||||
)
|
||||
return false
|
||||
}
|
||||
val mergedCorrelation = if (useSpatialModel || useSabreModel) {
|
||||
metadata.mgcDenoiseCorrelation
|
||||
} else null
|
||||
val coreTuning = PhotonSensorSizeTuning.resolve(metadata.rawMaxQualityTuningSensorAreaMm2)
|
||||
// Only a newly constructed single-frame model uses the seed. Fused models must
|
||||
// supply their spectrum; measured/prepared spectra retain their own amplitude.
|
||||
val defaultCorrelation = if (!useSpatialModel && !useSabreModel) {
|
||||
FloatArray(128) { coreTuning.denoise.noiseSpectrumSeed }
|
||||
} else null
|
||||
val lumaCorrelation = applyFusionCorrelationScale(
|
||||
correlation = preparedYuvNoiseModel?.lumaCorrelation ?: mergedCorrelation ?: defaultCorrelation,
|
||||
scale = coreTuning.fusion.noiseCorrelationScale,
|
||||
enabled = useSabreModel,
|
||||
)
|
||||
val chromaCorrelation = applyFusionCorrelationScale(
|
||||
correlation = preparedYuvNoiseModel?.chromaCorrelation ?: mergedCorrelation ?: defaultCorrelation,
|
||||
scale = coreTuning.fusion.noiseCorrelationScale,
|
||||
enabled = useSabreModel,
|
||||
)
|
||||
if ((useSpatialModel || useSabreModel) &&
|
||||
(!validCorrelation(lumaCorrelation) || !validCorrelation(chromaCorrelation))
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"MGC denoise rejected missing/malformed $pass Y/C correlation spectrum",
|
||||
)
|
||||
return false
|
||||
}
|
||||
val spatialStrengthMap = metadata.mgcSpatialStrengthMap.takeIf {
|
||||
useSpatialModel
|
||||
}
|
||||
if (useSpatialModel && spatialStrengthMap?.let {
|
||||
it.width == (fullWidth + 3) / 4 &&
|
||||
it.height == (fullHeight + 3) / 4 &&
|
||||
it.q8.size == it.width * it.height
|
||||
} != true
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"MGC denoise rejected Spatial strength map: " +
|
||||
"full=${fullWidth}x$fullHeight map=${spatialStrengthMap?.let {
|
||||
"${it.width}x${it.height}/${it.q8.size}"
|
||||
} ?: "none"}",
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
val rgbRead: FloatArray
|
||||
val rgbShot: FloatArray
|
||||
if (useSpatialModel || useSabreModel) {
|
||||
rgbRead = metadata.mgcDenoiseReadNoise?.copyOf()
|
||||
?: run {
|
||||
PLog.e(TAG, "MGC denoise rejected missing $pass read coefficients")
|
||||
return false
|
||||
}
|
||||
rgbShot = metadata.mgcDenoiseShotNoise?.copyOf()
|
||||
?: run {
|
||||
PLog.e(TAG, "MGC denoise rejected missing $pass shot coefficients")
|
||||
return false
|
||||
}
|
||||
if (!validRgbNoise(rgbRead) || !validRgbNoise(rgbShot) ||
|
||||
(rgbRead.none { it > 0f } && rgbShot.none { it > 0f })
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"MGC denoise rejected malformed $pass noise coefficients: " +
|
||||
"read=${rgbRead.contentToString()} shot=${rgbShot.contentToString()}",
|
||||
)
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
val resolvedNoise = resolveUserAdjustmentCameraRgbNoise(metadata)
|
||||
if (resolvedNoise == null) {
|
||||
PLog.w(TAG, "MGC denoise skipped: RAW noise profile is unavailable")
|
||||
return false
|
||||
}
|
||||
rgbShot = resolvedNoise.shot
|
||||
rgbRead = resolvedNoise.read
|
||||
}
|
||||
val useLensShadingForStrength =
|
||||
(useSpatialModel || useSabreModel || applyLensShadingToDenoiseStrength) &&
|
||||
hasValidLensShadingMap(metadata)
|
||||
val rgbWhiteBalance = normalizedRgbWhiteBalance(metadata.whiteBalanceGains)
|
||||
val selectedLumaTuningPoints = if (useSabreModel) {
|
||||
sabreLumaTuningPoints.map { point ->
|
||||
point.copy(
|
||||
tuning = applySabreLumaNodeOverrides(
|
||||
tuning = point.tuning,
|
||||
snr = point.snr,
|
||||
nodes = coreTuning.denoise.sabreLumaNodes,
|
||||
revertNodes = coreTuning.denoise.sabreLumaRevertNodes,
|
||||
outlierNodes = coreTuning.denoise.sabreLumaOutlierNodes,
|
||||
),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
lumaTuningPoints
|
||||
}
|
||||
val lumaTuning = applyCoreDenoiseScales(
|
||||
tuning = interpolateTuning(tuningSnr, selectedLumaTuningPoints),
|
||||
globalStrengthScale = finiteLumaScale,
|
||||
strengthLevelScales = coreTuning.denoise.lumaStrengthScale.toFloatArray(),
|
||||
revertLevelScales = coreTuning.denoise.detailReconstructionScale.toFloatArray(),
|
||||
outlierLevelScales = coreTuning.denoise.outlierRejectionScale.toFloatArray(),
|
||||
)
|
||||
val chromaTuning = applyCoreDenoiseScales(
|
||||
tuning = interpolateTuning(tuningSnr, chromaTuningPoints),
|
||||
globalStrengthScale = finiteChromaScale,
|
||||
strengthLevelScales = coreTuning.denoise.chromaStrengthScale.toFloatArray(),
|
||||
revertLevelScales = FloatArray(5) { 1f },
|
||||
outlierLevelScales = FloatArray(5) { 1f },
|
||||
)
|
||||
// MGC process_raw enables MeasureMoire only for a standard Bayer
|
||||
// capture at exact 1x output. The AOT consumes RawToYuv's Y plane, so
|
||||
// this remains valid when the current handoff already contains RGB.
|
||||
val measureMoireEnabled = chromaEnabled &&
|
||||
metadata.cfaPattern in RawMetadata.CFA_RGGB..RawMetadata.CFA_BGGR &&
|
||||
outputScale == 1f
|
||||
rgba16f.clear()
|
||||
val result = nativeDenoiseRgba16f(
|
||||
rgbaBuffer = rgba16f,
|
||||
width = width,
|
||||
height = height,
|
||||
globalOriginX = globalOriginX,
|
||||
globalOriginY = globalOriginY,
|
||||
fullWidth = fullWidth,
|
||||
fullHeight = fullHeight,
|
||||
inputIsBayer = inputLayout == InputLayout.NORMALIZED_BAYER16,
|
||||
cfaPattern = metadata.cfaPattern,
|
||||
measureMoireEnabled = measureMoireEnabled,
|
||||
applyLensShadingInBayerAot = applyLensShadingInBayerAot,
|
||||
lensShading = metadata.lensShadingMap.takeIf { useLensShadingForStrength },
|
||||
lensWidth = if (useLensShadingForStrength) metadata.lensShadingMapWidth else 0,
|
||||
lensHeight = if (useLensShadingForStrength) metadata.lensShadingMapHeight else 0,
|
||||
normalizedRgbShot = rgbShot,
|
||||
normalizedRgbRead = rgbRead,
|
||||
normalizedRgbWhiteBalance = rgbWhiteBalance,
|
||||
preparedNormalizedYuvRead = preparedYuvNoiseModel?.normalizedRead,
|
||||
preparedNormalizedLumaShot = preparedYuvNoiseModel?.normalizedLumaShot ?: 0f,
|
||||
preparedNormalizedLumaQuadratic =
|
||||
preparedYuvNoiseModel?.normalizedLumaQuadratic ?: 0f,
|
||||
preparedNormalizedChromaShot = preparedYuvNoiseModel?.normalizedChromaShot ?: 0f,
|
||||
preparedNormalizedChromaQuadratic =
|
||||
preparedYuvNoiseModel?.normalizedChromaQuadratic ?: 0f,
|
||||
lumaCorrelation = lumaCorrelation,
|
||||
chromaCorrelation = chromaCorrelation,
|
||||
denoiseResponseOffset = coreTuning.denoise.frequencyResponse.responseOffset,
|
||||
denoiseResponseCosineOffset = coreTuning.denoise.frequencyResponse.cosineOffset,
|
||||
spatialStrengthQ8 = spatialStrengthMap?.q8,
|
||||
spatialStrengthWidth = spatialStrengthMap?.width ?: 0,
|
||||
spatialStrengthHeight = spatialStrengthMap?.height ?: 0,
|
||||
lumaEnabled = lumaEnabled,
|
||||
chromaEnabled = chromaEnabled,
|
||||
lumaStrength = lumaTuning.strength,
|
||||
lumaOutlierDistance = lumaTuning.outlierDistance,
|
||||
lumaRevertFactor = lumaTuning.revertFactor,
|
||||
chromaStrength = chromaTuning.strength,
|
||||
chromaOutlierThreshold = chromaTuning.outlierDistance,
|
||||
diagnosticsEnabled = RawStackRuntimeDebug.mgcFullResolutionDenoiseDiagnosticsEnabled,
|
||||
)
|
||||
rgba16f.position(0)
|
||||
if (result != 0) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"MGC static denoise kernel failed: " +
|
||||
"result=0x${result.toString(16)} size=${width}x$height " +
|
||||
"origin=($globalOriginX,$globalOriginY) " +
|
||||
"input=$inputLayout " +
|
||||
"luma=$lumaEnabled chroma=$chromaEnabled " +
|
||||
"measureMoire=$measureMoireEnabled outputScale=$outputScale",
|
||||
)
|
||||
return false
|
||||
}
|
||||
PLog.d(
|
||||
TAG,
|
||||
"MGC static denoise complete: size=${width}x$height " +
|
||||
"origin=($globalOriginX,$globalOriginY) input=$inputLayout " +
|
||||
"snr=$tuningSnr pass=$pass " +
|
||||
"luma=$lumaEnabled($finiteLumaScale) " +
|
||||
"chroma=$chromaEnabled($finiteChromaScale) " +
|
||||
"measureMoire=$measureMoireEnabled outputScale=$outputScale " +
|
||||
"rgbShot=${rgbShot.contentToString()} " +
|
||||
"rgbRead=${rgbRead.contentToString()} " +
|
||||
"rgbWb=${rgbWhiteBalance.contentToString()} " +
|
||||
"qualityTuningSensorAreaMm2=${metadata.rawMaxQualityTuningSensorAreaMm2} " +
|
||||
"tuningInterpolation=linear " +
|
||||
"lumaScales=${coreTuning.denoise.lumaStrengthScale} " +
|
||||
"detailReconstructionScales=${coreTuning.denoise.detailReconstructionScale} " +
|
||||
"outlierRejectionScales=${coreTuning.denoise.outlierRejectionScale} " +
|
||||
"chromaScales=${coreTuning.denoise.chromaStrengthScale} " +
|
||||
"frequencyResponse=${coreTuning.denoise.frequencyResponse} " +
|
||||
"noiseCorrelationScale=${coreTuning.fusion.noiseCorrelationScale} " +
|
||||
"lumaStrength=${lumaTuning.strength.contentToString()} " +
|
||||
"lumaOutlier=${lumaTuning.outlierDistance.contentToString()} " +
|
||||
"lumaRevert=${lumaTuning.revertFactor.contentToString()} " +
|
||||
"chromaStrength=${chromaTuning.strength.contentToString()} " +
|
||||
"chromaOutlier=${chromaTuning.outlierDistance.contentToString()} " +
|
||||
"preparedYuvRead=${preparedYuvNoiseModel?.normalizedRead?.contentToString()} " +
|
||||
"preparedLumaShot=${preparedYuvNoiseModel?.normalizedLumaShot} " +
|
||||
"preparedLumaQuadratic=${preparedYuvNoiseModel?.normalizedLumaQuadratic} " +
|
||||
"preparedChromaShot=${preparedYuvNoiseModel?.normalizedChromaShot} " +
|
||||
"preparedChromaQuadratic=${preparedYuvNoiseModel?.normalizedChromaQuadratic} " +
|
||||
"strengthMap=${spatialStrengthMap?.let {
|
||||
"${it.width}x${it.height}"
|
||||
} ?: "identity"} " +
|
||||
"lsc=${if (useLensShadingForStrength) {
|
||||
"${metadata.lensShadingMapWidth}x${metadata.lensShadingMapHeight}"
|
||||
} else {
|
||||
"identity"
|
||||
}} " +
|
||||
"lumaCorrelation=${if (lumaCorrelation == null) "identity" else "propagated"} " +
|
||||
"chromaCorrelation=${if (chromaCorrelation == null) {
|
||||
"identity"
|
||||
} else {
|
||||
"propagated"
|
||||
}}",
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun validPreparedYuvNoise(model: PreparedYuvNoiseModel): Boolean =
|
||||
validRgbNoise(model.normalizedRead) &&
|
||||
model.normalizedLumaShot.isFinite() && model.normalizedLumaShot >= 0f &&
|
||||
model.normalizedLumaQuadratic.isFinite() &&
|
||||
model.normalizedLumaQuadratic >= 0f &&
|
||||
model.normalizedChromaShot.isFinite() && model.normalizedChromaShot >= 0f &&
|
||||
model.normalizedChromaQuadratic.isFinite() &&
|
||||
model.normalizedChromaQuadratic >= 0f &&
|
||||
validCorrelation(model.lumaCorrelation) &&
|
||||
validCorrelation(model.chromaCorrelation) &&
|
||||
(model.normalizedRead.any { it > 0f } ||
|
||||
model.normalizedLumaShot > 0f || model.normalizedLumaQuadratic > 0f ||
|
||||
model.normalizedChromaShot > 0f || model.normalizedChromaQuadratic > 0f)
|
||||
|
||||
private fun validCorrelation(correlation: FloatArray?): Boolean =
|
||||
correlation?.let { values ->
|
||||
values.size == 128 && values.all { it.isFinite() && it >= 0f }
|
||||
} == true
|
||||
|
||||
internal fun resolveUserAdjustmentCameraRgbNoise(
|
||||
metadata: RawMetadata,
|
||||
): NormalizedCameraRgbNoise? {
|
||||
val rawNoise = when (metadata.noiseProfileLayout) {
|
||||
RawNoiseProfileLayout.CAMERA2_CFA ->
|
||||
RawNoiseModel.fromCamera2NoiseProfile(metadata.channelNoiseProfile)
|
||||
RawNoiseProfileLayout.DNG_RGB ->
|
||||
RawNoiseModel.fromDngNoiseProfile(metadata.channelNoiseProfile)
|
||||
RawNoiseProfileLayout.CANONICAL_BAYER -> {
|
||||
if (metadata.channelNoiseProfile.size < 8) return null
|
||||
RawNoiseModel.fromCanonicalBayerChannels(
|
||||
shotNoise = FloatArray(4) { metadata.channelNoiseProfile[it * 2] },
|
||||
readNoise = FloatArray(4) { metadata.channelNoiseProfile[it * 2 + 1] },
|
||||
)
|
||||
}
|
||||
RawNoiseProfileLayout.NONE -> RawNoiseModel.EMPTY
|
||||
}
|
||||
val bayerShot = rawNoise.normalizedShotNoiseForShader(metadata.cfaPattern)
|
||||
val bayerRead = rawNoise.normalizedReadNoiseForShader(metadata.cfaPattern)
|
||||
if (bayerShot.none { it > 0f } && bayerRead.none { it > 0f }) return null
|
||||
return NormalizedCameraRgbNoise(
|
||||
read = RawNoiseModel.bayerNoiseModelToRgb(bayerRead),
|
||||
shot = RawNoiseModel.bayerNoiseModelToRgb(bayerShot),
|
||||
)
|
||||
}
|
||||
|
||||
private fun hasValidLensShadingMap(metadata: RawMetadata): Boolean {
|
||||
val map = metadata.lensShadingMap ?: return false
|
||||
val expectedSize = metadata.lensShadingMapWidth.toLong() *
|
||||
metadata.lensShadingMapHeight.toLong() * 4L
|
||||
return metadata.lensShadingMapWidth > 0 && metadata.lensShadingMapHeight > 0 &&
|
||||
expectedSize in 1L..Int.MAX_VALUE.toLong() && map.size == expectedSize.toInt() &&
|
||||
map.all { it.isFinite() && it > 0f }
|
||||
}
|
||||
|
||||
internal fun applyLumaStrengthScales(
|
||||
tuning: Tuning,
|
||||
globalScale: Float,
|
||||
levelScales: FloatArray,
|
||||
): Tuning = applyCoreDenoiseScales(
|
||||
tuning = tuning,
|
||||
globalStrengthScale = globalScale,
|
||||
strengthLevelScales = levelScales,
|
||||
revertLevelScales = FloatArray(tuning.strength.size) { 1f },
|
||||
outlierLevelScales = FloatArray(tuning.strength.size) { 1f },
|
||||
)
|
||||
|
||||
/**
|
||||
* Applies Photon controls to the three independent denoise protobuf fields:
|
||||
* strength, revert factor (detail reconstruction), and outlier distance.
|
||||
*/
|
||||
internal fun applyCoreDenoiseScales(
|
||||
tuning: Tuning,
|
||||
globalStrengthScale: Float,
|
||||
strengthLevelScales: FloatArray,
|
||||
revertLevelScales: FloatArray,
|
||||
outlierLevelScales: FloatArray,
|
||||
): Tuning {
|
||||
val levelCount = tuning.strength.size
|
||||
require(tuning.revertFactor.size == levelCount && tuning.outlierDistance.size == levelCount)
|
||||
require(
|
||||
strengthLevelScales.size == levelCount &&
|
||||
revertLevelScales.size == levelCount &&
|
||||
outlierLevelScales.size == levelCount,
|
||||
) { "Denoise control count does not match the tuning level count" }
|
||||
require(
|
||||
globalStrengthScale.isFinite() &&
|
||||
strengthLevelScales.all(Float::isFinite) &&
|
||||
revertLevelScales.all(Float::isFinite) &&
|
||||
outlierLevelScales.all(Float::isFinite),
|
||||
) { "Denoise control is not finite" }
|
||||
return Tuning(
|
||||
strength = FloatArray(levelCount) { index ->
|
||||
tuning.strength[index] * globalStrengthScale * strengthLevelScales[index]
|
||||
},
|
||||
revertFactor = FloatArray(levelCount) { index ->
|
||||
tuning.revertFactor[index] * revertLevelScales[index]
|
||||
},
|
||||
outlierDistance = FloatArray(levelCount) { index ->
|
||||
tuning.outlierDistance[index] * outlierLevelScales[index]
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
internal fun applySabreLumaNodeOverrides(
|
||||
tuning: Tuning,
|
||||
snr: Float,
|
||||
nodes: PhotonSabreLumaTuningNodes,
|
||||
revertNodes: PhotonSabreLumaTuningNodes = PhotonSabreLumaTuningNodes.DEFAULT,
|
||||
outlierNodes: PhotonSabreLumaTuningNodes = PhotonSabreLumaTuningNodes.DEFAULT,
|
||||
): Tuning {
|
||||
fun overrideField(
|
||||
original: FloatArray,
|
||||
overrides: PhotonSabreLumaTuningNodes,
|
||||
allowNegative: Boolean = false,
|
||||
): FloatArray {
|
||||
val row = overrides.normalized(allowNegative).valuesForSnr(snr) ?: return original.copyOf()
|
||||
require(row.size == original.size)
|
||||
return FloatArray(original.size) { index -> row[index] ?: original[index] }
|
||||
}
|
||||
return tuning.copy(
|
||||
strength = overrideField(tuning.strength, nodes),
|
||||
revertFactor = overrideField(tuning.revertFactor, revertNodes, allowNegative = true),
|
||||
outlierDistance = overrideField(tuning.outlierDistance, outlierNodes, allowNegative = true),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun applyFusionCorrelationScale(
|
||||
correlation: FloatArray?,
|
||||
scale: Float,
|
||||
enabled: Boolean,
|
||||
): FloatArray? {
|
||||
if (!enabled) return correlation
|
||||
require(scale.isFinite() && scale >= 0f)
|
||||
if (correlation == null && scale == 1f) return null
|
||||
return FloatArray(128) { index -> (correlation?.get(index) ?: 1f) * scale }
|
||||
}
|
||||
|
||||
private fun validRgbNoise(values: FloatArray): Boolean =
|
||||
values.size == 3 && values.all { it.isFinite() && it >= 0f }
|
||||
|
||||
/**
|
||||
* MGC's BayerRawToYuv/RgbRawToYuv boundary applies channel gains before
|
||||
* denoising. Spatial/VGN exports un-white-balanced camera RGB for Linear
|
||||
* DNG, so the native bridge enters that same working domain and removes
|
||||
* the gains again after YUV -> RGB.
|
||||
*/
|
||||
internal fun normalizedRgbWhiteBalance(gains: FloatArray): FloatArray {
|
||||
fun safeGain(index: Int, fallback: Float): Float {
|
||||
val value = gains.getOrElse(index) { fallback }
|
||||
return value.takeIf { it.isFinite() && it > 0f } ?: fallback
|
||||
}
|
||||
val greenEven = safeGain(1, 1f)
|
||||
val greenOdd = safeGain(2, greenEven)
|
||||
val green = (0.5f * (greenEven + greenOdd))
|
||||
.takeIf { it.isFinite() && it > 0f }
|
||||
?: 1f
|
||||
return floatArrayOf(
|
||||
(safeGain(0, green) / green).coerceIn(1e-3f, 64f),
|
||||
1f,
|
||||
(safeGain(3, green) / green).coerceIn(1e-3f, 64f),
|
||||
)
|
||||
}
|
||||
|
||||
/** Exact upper-bound clamp and linear SNR interpolation from libgcastartup.so+0x33ec5d4. */
|
||||
internal fun interpolateTuning(
|
||||
snr: Float,
|
||||
points: List<TuningPoint>,
|
||||
): Tuning {
|
||||
val finiteSnr = snr.takeIf { it.isFinite() && it >= 0f }
|
||||
?: points.first().snr
|
||||
val upperIndex = points.indexOfFirst { it.snr > finiteSnr }
|
||||
if (upperIndex < 0) return points.last().tuning.copyArrays()
|
||||
if (upperIndex == 0) return points.first().tuning.copyArrays()
|
||||
val lower = points[upperIndex - 1]
|
||||
val upper = points[upperIndex]
|
||||
val amount = (
|
||||
(finiteSnr - lower.snr) /
|
||||
(upper.snr - lower.snr)
|
||||
).coerceIn(0f, 1f)
|
||||
val lowerAmount = 1f - amount
|
||||
fun interpolate(
|
||||
first: FloatArray,
|
||||
second: FloatArray,
|
||||
): FloatArray = FloatArray(5) { index ->
|
||||
// libgcastartup 0x54b3794..0x54b37ac: two FMULs, then FADD (not FMADD).
|
||||
lowerAmount * first[index] + second[index] * amount
|
||||
}
|
||||
return Tuning(
|
||||
strength = interpolate(
|
||||
lower.tuning.strength,
|
||||
upper.tuning.strength,
|
||||
),
|
||||
revertFactor = interpolate(
|
||||
lower.tuning.revertFactor,
|
||||
upper.tuning.revertFactor,
|
||||
),
|
||||
outlierDistance = interpolate(
|
||||
lower.tuning.outlierDistance,
|
||||
upper.tuning.outlierDistance,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun Tuning.copyArrays(): Tuning = Tuning(
|
||||
strength.copyOf(),
|
||||
revertFactor.copyOf(),
|
||||
outlierDistance.copyOf(),
|
||||
)
|
||||
|
||||
private class ProtoReader(
|
||||
private val bytes: ByteArray,
|
||||
private var position: Int = 0,
|
||||
private val limit: Int = bytes.size,
|
||||
) {
|
||||
fun hasRemaining(): Boolean = position < limit
|
||||
|
||||
fun readTag(): Pair<Int, Int> {
|
||||
val tag = readVarint().toInt()
|
||||
return (tag ushr 3) to (tag and 7)
|
||||
}
|
||||
|
||||
fun readMessage(): ProtoReader {
|
||||
val length = readVarint().toInt()
|
||||
require(length >= 0 && position + length <= limit)
|
||||
val child = ProtoReader(bytes, position, position + length)
|
||||
position += length
|
||||
return child
|
||||
}
|
||||
|
||||
fun readFixed32Float(): Float {
|
||||
require(position + 4 <= limit)
|
||||
val bits =
|
||||
(bytes[position].toInt() and 0xff) or
|
||||
((bytes[position + 1].toInt() and 0xff) shl 8) or
|
||||
((bytes[position + 2].toInt() and 0xff) shl 16) or
|
||||
((bytes[position + 3].toInt() and 0xff) shl 24)
|
||||
position += 4
|
||||
return Float.fromBits(bits)
|
||||
}
|
||||
|
||||
fun skip(wireType: Int) {
|
||||
when (wireType) {
|
||||
0 -> readVarint()
|
||||
1 -> position += 8
|
||||
2 -> position += readVarint().toInt()
|
||||
5 -> position += 4
|
||||
else -> error("Unsupported protobuf wire type $wireType")
|
||||
}
|
||||
require(position <= limit)
|
||||
}
|
||||
|
||||
private fun readVarint(): Long {
|
||||
var result = 0L
|
||||
var shift = 0
|
||||
while (shift < 64) {
|
||||
require(position < limit)
|
||||
val value = bytes[position++].toInt() and 0xff
|
||||
result = result or ((value and 0x7f).toLong() shl shift)
|
||||
if (value and 0x80 == 0) return result
|
||||
shift += 7
|
||||
}
|
||||
error("Malformed protobuf varint")
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseTuning(bytes: ByteArray): List<TuningPoint> {
|
||||
val result = ArrayList<TuningPoint>()
|
||||
val root = ProtoReader(bytes)
|
||||
while (root.hasRemaining()) {
|
||||
val (field, wire) = root.readTag()
|
||||
if (field != 1 || wire != 2) {
|
||||
root.skip(wire)
|
||||
continue
|
||||
}
|
||||
val point = root.readMessage()
|
||||
val strength = ArrayList<Float>(5)
|
||||
val revert = ArrayList<Float>(5)
|
||||
val outlier = ArrayList<Float>(5)
|
||||
var snr: Float? = null
|
||||
while (point.hasRemaining()) {
|
||||
val (pointField, pointWire) = point.readTag()
|
||||
when {
|
||||
pointField == 1 && pointWire == 2 -> {
|
||||
val level = point.readMessage()
|
||||
var levelStrength = 0f
|
||||
var levelRevert = 0f
|
||||
var levelOutlier = 0f
|
||||
while (level.hasRemaining()) {
|
||||
val (levelField, levelWire) = level.readTag()
|
||||
if (levelWire != 5) {
|
||||
level.skip(levelWire)
|
||||
continue
|
||||
}
|
||||
when (levelField) {
|
||||
1 -> levelStrength = level.readFixed32Float()
|
||||
2 -> levelRevert = level.readFixed32Float()
|
||||
3 -> levelOutlier = level.readFixed32Float()
|
||||
else -> level.skip(levelWire)
|
||||
}
|
||||
}
|
||||
strength += levelStrength
|
||||
revert += levelRevert
|
||||
outlier += levelOutlier
|
||||
}
|
||||
|
||||
pointField == 2 && pointWire == 2 -> {
|
||||
val snrMessage = point.readMessage()
|
||||
while (snrMessage.hasRemaining()) {
|
||||
val (snrField, snrWire) = snrMessage.readTag()
|
||||
if (snrField == 1 && snrWire == 5) {
|
||||
snr = snrMessage.readFixed32Float()
|
||||
} else {
|
||||
snrMessage.skip(snrWire)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else -> point.skip(pointWire)
|
||||
}
|
||||
}
|
||||
require(strength.size == 5 && revert.size == 5 && outlier.size == 5)
|
||||
val pointSnr = requireNotNull(snr)
|
||||
result += TuningPoint(
|
||||
snr = pointSnr,
|
||||
tuning = Tuning(
|
||||
strength.toFloatArray(),
|
||||
revert.toFloatArray(),
|
||||
outlier.toFloatArray(),
|
||||
),
|
||||
)
|
||||
}
|
||||
return result.sortedBy(TuningPoint::snr)
|
||||
}
|
||||
|
||||
private external fun nativeDenoiseRgba16f(
|
||||
rgbaBuffer: ByteBuffer,
|
||||
width: Int,
|
||||
height: Int,
|
||||
globalOriginX: Int,
|
||||
globalOriginY: Int,
|
||||
fullWidth: Int,
|
||||
fullHeight: Int,
|
||||
inputIsBayer: Boolean,
|
||||
cfaPattern: Int,
|
||||
measureMoireEnabled: Boolean,
|
||||
applyLensShadingInBayerAot: Boolean,
|
||||
lensShading: FloatArray?,
|
||||
lensWidth: Int,
|
||||
lensHeight: Int,
|
||||
normalizedRgbShot: FloatArray,
|
||||
normalizedRgbRead: FloatArray,
|
||||
normalizedRgbWhiteBalance: FloatArray,
|
||||
preparedNormalizedYuvRead: FloatArray?,
|
||||
preparedNormalizedLumaShot: Float,
|
||||
preparedNormalizedLumaQuadratic: Float,
|
||||
preparedNormalizedChromaShot: Float,
|
||||
preparedNormalizedChromaQuadratic: Float,
|
||||
lumaCorrelation: FloatArray?,
|
||||
chromaCorrelation: FloatArray?,
|
||||
denoiseResponseOffset: Float,
|
||||
denoiseResponseCosineOffset: Float,
|
||||
spatialStrengthQ8: ShortArray?,
|
||||
spatialStrengthWidth: Int,
|
||||
spatialStrengthHeight: Int,
|
||||
lumaEnabled: Boolean,
|
||||
chromaEnabled: Boolean,
|
||||
lumaStrength: FloatArray,
|
||||
lumaOutlierDistance: FloatArray,
|
||||
lumaRevertFactor: FloatArray,
|
||||
chromaStrength: FloatArray,
|
||||
chromaOutlierThreshold: FloatArray,
|
||||
diagnosticsEnabled: Boolean,
|
||||
): Int
|
||||
}
|
||||
@@ -32,7 +32,7 @@ internal class MgcGuidedUpsample(private val transfer: RawFloatTextureTransfer)
|
||||
try {
|
||||
transfer.read(texture, width, height, capacityPixels, label = "guidedPrepare") { rgba ->
|
||||
handle = nativePrepare(rgba, width, height, resolution.log2Downsample,
|
||||
MgcFullResolutionDenoise.normalizedRgbWhiteBalance(gains))
|
||||
normalizedRgbWhiteBalance(gains))
|
||||
check(handle != 0L) { "MGC linear guide/BoxDownsample preparation failed" }
|
||||
}
|
||||
cameraTexture = createTexture()
|
||||
@@ -140,3 +140,24 @@ internal class MgcGuidedUpsample(private val transfer: RawFloatTextureTransfer)
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The guide's linear YUV boundary applies channel gains normalized to the green mean; the
|
||||
* native bridge removes them again after YUV -> RGB.
|
||||
*/
|
||||
private fun normalizedRgbWhiteBalance(gains: FloatArray): FloatArray {
|
||||
fun safeGain(index: Int, fallback: Float): Float {
|
||||
val value = gains.getOrElse(index) { fallback }
|
||||
return value.takeIf { it.isFinite() && it > 0f } ?: fallback
|
||||
}
|
||||
val greenEven = safeGain(1, 1f)
|
||||
val greenOdd = safeGain(2, greenEven)
|
||||
val green = (0.5f * (greenEven + greenOdd))
|
||||
.takeIf { it.isFinite() && it > 0f }
|
||||
?: 1f
|
||||
return floatArrayOf(
|
||||
(safeGain(0, green) / green).coerceIn(1e-3f, 64f),
|
||||
1f,
|
||||
(safeGain(3, green) / green).coerceIn(1e-3f, 64f),
|
||||
)
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
/**
|
||||
* Process-local Q8 variance multiplier produced by MGC Spatial.
|
||||
*
|
||||
* It is consumed by the default pre-DNG denoise pass and is deliberately not
|
||||
* serialized into DNG metadata.
|
||||
*/
|
||||
class MgcSpatialStrengthMap(
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val q8: ShortArray,
|
||||
) {
|
||||
init {
|
||||
require(width > 0 && height > 0)
|
||||
require(q8.size == width * height)
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean =
|
||||
other is MgcSpatialStrengthMap &&
|
||||
width == other.width &&
|
||||
height == other.height &&
|
||||
q8.contentEquals(other.q8)
|
||||
|
||||
override fun hashCode(): Int {
|
||||
var result = width
|
||||
result = 31 * result + height
|
||||
result = 31 * result + q8.contentHashCode()
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* V25 SpatialMerge::Finish keeps the AOT's complete RAW/4 cells in place and
|
||||
* initializes strength outside that region to Q8 identity (256). The extra
|
||||
* partial cell needed by our full-resolution denoiser is storage coverage,
|
||||
* not a change of image scale.
|
||||
*/
|
||||
fun withIdentityBorder(fullWidth: Int, fullHeight: Int): MgcSpatialStrengthMap {
|
||||
require(width == fullWidth / 4 && height == fullHeight / 4)
|
||||
val coveredWidth = (fullWidth + 3) / 4
|
||||
val coveredHeight = (fullHeight + 3) / 4
|
||||
if (width == coveredWidth && height == coveredHeight) return this
|
||||
val covered = identityForFullResolution(fullWidth, fullHeight)
|
||||
for (y in 0 until height) {
|
||||
q8.copyInto(covered.q8, y * coveredWidth, y * width, (y + 1) * width)
|
||||
}
|
||||
return covered
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Q8 identity multiplier used by MGC before a Spatial model is available. */
|
||||
private const val IDENTITY_Q8 = 256
|
||||
|
||||
fun identityForFullResolution(
|
||||
fullWidth: Int,
|
||||
fullHeight: Int,
|
||||
): MgcSpatialStrengthMap {
|
||||
require(fullWidth > 0 && fullHeight > 0)
|
||||
val strengthWidth = (fullWidth + 3) / 4
|
||||
val strengthHeight = (fullHeight + 3) / 4
|
||||
return MgcSpatialStrengthMap(
|
||||
width = strengthWidth,
|
||||
height = strengthHeight,
|
||||
q8 = ShortArray(strengthWidth * strengthHeight) {
|
||||
IDENTITY_Q8.toShort()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.util.Base64
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/**
|
||||
* Lens shading gain already multiplied into the pixels before the denoiser
|
||||
* (docs/photon-multiscale-denoise.md §3.2).
|
||||
*
|
||||
* Layout and sampling are those of the merge output transforms (GlesMgcRawSpatialShaders
|
||||
* normalizeRgb / normalizeAotRgb, GlesMgcRawSabreShaders output transform): Camera2
|
||||
* LensShadingMap gains interleaved as R, Ge, Go, B; whole-image UV (p + 0.5) / imageSize with
|
||||
* bilinear filtering; green uses the mean of the two green gains.
|
||||
*/
|
||||
data class RawAppliedLensShading(
|
||||
val gains: FloatArray,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
) {
|
||||
val isValid: Boolean
|
||||
get() = width > 0 && height > 0 && gains.size == width * height * CHANNELS &&
|
||||
gains.all { it.isFinite() && it > 0f }
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (other !is RawAppliedLensShading) return false
|
||||
return width == other.width && height == other.height && gains.contentEquals(other.gains)
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
var result = gains.contentHashCode()
|
||||
result = 31 * result + width
|
||||
result = 31 * result + height
|
||||
return result
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val CHANNELS = 4
|
||||
|
||||
/**
|
||||
* The map a merge applied: MultiFrameStacker.validLensShadingOrNull accepts a map holding at
|
||||
* least width * height * 4 gains and samples only that prefix.
|
||||
*/
|
||||
fun fromCamera2(map: FloatArray?, width: Int, height: Int): RawAppliedLensShading? {
|
||||
if (map == null || width <= 0 || height <= 0 || map.size < width * height * CHANNELS) return null
|
||||
return RawAppliedLensShading(map.copyOf(width * height * CHANNELS), width, height)
|
||||
.takeIf { it.isValid }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Gallery-metadata persistence of [RawAppliedLensShading], alongside RawPhotonHdrMetadata. */
|
||||
internal object RawAppliedLensShadingMetadata {
|
||||
private const val GAINS_PROPERTY = "photonAppliedLensShadingGains"
|
||||
private const val SIZE_PROPERTY = "photonAppliedLensShadingSize"
|
||||
private const val CONTRACT_PROPERTY = "photonAppliedLensShadingContract"
|
||||
private const val CURRENT_CONTRACT = "camera2_r_ge_go_b_image_uv_bilinear_f32le_v1"
|
||||
|
||||
fun write(properties: Map<String, String>, value: RawAppliedLensShading?): Map<String, String> {
|
||||
val out = properties.toMutableMap()
|
||||
out.remove(GAINS_PROPERTY)
|
||||
out.remove(SIZE_PROPERTY)
|
||||
out.remove(CONTRACT_PROPERTY)
|
||||
if (value == null) return out
|
||||
require(value.isValid) { "Applied lens shading map is malformed" }
|
||||
val bytes = ByteBuffer.allocate(value.gains.size * Float.SIZE_BYTES)
|
||||
.order(ByteOrder.LITTLE_ENDIAN)
|
||||
value.gains.forEach(bytes::putFloat)
|
||||
out[GAINS_PROPERTY] = Base64.encodeToString(bytes.array(), Base64.NO_WRAP)
|
||||
out[SIZE_PROPERTY] = "${value.width}x${value.height}"
|
||||
out[CONTRACT_PROPERTY] = CURRENT_CONTRACT
|
||||
return out
|
||||
}
|
||||
|
||||
fun read(properties: Map<String, String>): RawAppliedLensShading? {
|
||||
if (properties[CONTRACT_PROPERTY] != CURRENT_CONTRACT) return null
|
||||
val size = properties[SIZE_PROPERTY]?.split('x')?.mapNotNull(String::toIntOrNull)
|
||||
?.takeIf { it.size == 2 } ?: return null
|
||||
val encoded = properties[GAINS_PROPERTY] ?: return null
|
||||
val bytes = runCatching { Base64.decode(encoded, Base64.NO_WRAP) }.getOrNull() ?: return null
|
||||
if (bytes.size % Float.SIZE_BYTES != 0) return null
|
||||
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
|
||||
val gains = FloatArray(bytes.size / Float.SIZE_BYTES) { buffer.getFloat() }
|
||||
return RawAppliedLensShading(gains, size[0], size[1]).takeIf { it.isValid }
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,10 @@ import com.hinnka.mycamera.camera.AspectRatio
|
||||
import com.hinnka.mycamera.camera.CameraState
|
||||
import com.hinnka.mycamera.camera.RawBlackBorderCrop
|
||||
import com.hinnka.mycamera.data.ContentRepository
|
||||
import com.hinnka.mycamera.lut.ChromaDenoiseAlgorithm
|
||||
import com.hinnka.mycamera.raw.denoise.PhotonDenoiseDump
|
||||
import com.hinnka.mycamera.raw.denoise.PhotonLensShading
|
||||
import com.hinnka.mycamera.raw.denoise.PhotonMultiScaleDenoiser
|
||||
import com.hinnka.mycamera.raw.denoise.PhotonNoiseModel
|
||||
import com.hinnka.mycamera.ml.SharedDepthEstimator
|
||||
import com.hinnka.mycamera.processor.PhotonQualitySharpenTuning
|
||||
import com.hinnka.mycamera.processor.GlesGpuCompletion
|
||||
@@ -75,6 +78,8 @@ private data class ShadowsHighlightsParams(
|
||||
internal data class MgcSpatialGpuDenoiseResult(
|
||||
val gpuLinearRgbSource: GpuLinearRgbSource,
|
||||
val pixelsIncludeLensShadingCorrection: Boolean,
|
||||
/** Noise state of the output pixels (docs/photon-multiscale-denoise.md §2.2, §2.4). */
|
||||
val denoiseHistory: RawDenoiseHistory?,
|
||||
)
|
||||
|
||||
internal enum class MgcSpatialGpuDenoiseMode {
|
||||
@@ -226,11 +231,6 @@ class RawDemosaicProcessor {
|
||||
afRegions = baseMetadata?.afRegions,
|
||||
defaultCrop = defaultCrop,
|
||||
frameCount = baseMetadata?.frameCount ?: 1,
|
||||
mgcDenoiseCorrelation = baseMetadata?.mgcDenoiseCorrelation,
|
||||
mgcDenoiseReadNoise = baseMetadata?.mgcDenoiseReadNoise,
|
||||
mgcDenoiseShotNoise = baseMetadata?.mgcDenoiseShotNoise,
|
||||
mgcSpatialStrengthMap = baseMetadata?.mgcSpatialStrengthMap,
|
||||
mgcDenoiseTuningSnr = baseMetadata?.mgcDenoiseTuningSnr,
|
||||
mgcSharpenTuningSnr = baseMetadata?.mgcSharpenTuningSnr,
|
||||
mgcSharpenAttenuationScale = baseMetadata?.mgcSharpenAttenuationScale,
|
||||
rawMaxQualityTuningEnabled = baseMetadata?.rawMaxQualityTuningEnabled ?: false,
|
||||
@@ -959,8 +959,8 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
return@withContext null
|
||||
}
|
||||
if (applyDefaultDenoise && !MgcFullResolutionDenoise.ensureInitialized(context)) {
|
||||
PLog.e(TAG, "MGC $mode denoise kernels are unavailable")
|
||||
if (applyDefaultDenoise && !photonDenoiser.initialize()) {
|
||||
PLog.e(TAG, "Photon $mode denoise programs are unavailable")
|
||||
return@withContext null
|
||||
}
|
||||
|
||||
@@ -1007,10 +1007,10 @@ class RawDemosaicProcessor {
|
||||
var completed = false
|
||||
var borrowedTexture = false
|
||||
var workingFloatTexture = 0
|
||||
var demosaicNoiseTransfer: DemosaicNoiseTransfer? = null
|
||||
var denoisedTexture = 0
|
||||
var outputHistory = metadata.denoiseHistory
|
||||
val totalStartNs = System.nanoTime()
|
||||
try {
|
||||
if (applyDefaultDenoise) denoiseTransfer.prepare(width, height)
|
||||
val hasDirectFloatSource =
|
||||
gpuLinearRgbSource?.storage == GpuLinearRgbStorage.RGBA16F
|
||||
if (!hasDirectFloatSource) {
|
||||
@@ -1070,14 +1070,6 @@ class RawDemosaicProcessor {
|
||||
} else {
|
||||
pixelPreparationMetadata
|
||||
}
|
||||
if (applyDefaultDenoise) {
|
||||
demosaicNoiseTransfer = checkNotNull(
|
||||
demosaicNoisePropagationCalibrator.measure(
|
||||
quadMetadata,
|
||||
demosaicCalculationWbGains(quadMetadata),
|
||||
),
|
||||
) { "Unable to propagate Spatial noise through Quad Bayer demosaic" }
|
||||
}
|
||||
runQuadBayerDemosaic(
|
||||
metadata = quadMetadata,
|
||||
width = width,
|
||||
@@ -1097,14 +1089,6 @@ class RawDemosaicProcessor {
|
||||
} else {
|
||||
pixelPreparationMetadata
|
||||
}
|
||||
if (applyDefaultDenoise) {
|
||||
demosaicNoiseTransfer = checkNotNull(
|
||||
demosaicNoisePropagationCalibrator.measure(
|
||||
vgnMetadata,
|
||||
demosaicCalculationWbGains(vgnMetadata),
|
||||
),
|
||||
) { "Unable to propagate Spatial noise through VGN" }
|
||||
}
|
||||
runStandardBayerVgnDemosaic(
|
||||
metadata = vgnMetadata,
|
||||
width = width,
|
||||
@@ -1154,14 +1138,6 @@ class RawDemosaicProcessor {
|
||||
} else {
|
||||
pixelPreparationMetadata
|
||||
}
|
||||
if (applyDefaultDenoise) {
|
||||
demosaicNoiseTransfer = checkNotNull(
|
||||
demosaicNoisePropagationCalibrator.measure(
|
||||
quadMetadata,
|
||||
demosaicCalculationWbGains(quadMetadata),
|
||||
),
|
||||
) { "Unable to propagate Spatial noise through Quad Bayer demosaic" }
|
||||
}
|
||||
runQuadBayerDemosaic(
|
||||
metadata = quadMetadata,
|
||||
width = width,
|
||||
@@ -1190,14 +1166,6 @@ class RawDemosaicProcessor {
|
||||
} else {
|
||||
pixelPreparationMetadata
|
||||
}
|
||||
if (applyDefaultDenoise) {
|
||||
demosaicNoiseTransfer = checkNotNull(
|
||||
demosaicNoisePropagationCalibrator.measure(
|
||||
vgnMetadata,
|
||||
demosaicCalculationWbGains(vgnMetadata),
|
||||
),
|
||||
) { "Unable to propagate Spatial noise through VGN" }
|
||||
}
|
||||
runStandardBayerVgnDemosaic(
|
||||
metadata = vgnMetadata,
|
||||
width = width,
|
||||
@@ -1215,77 +1183,50 @@ class RawDemosaicProcessor {
|
||||
workingFloatTexture = demosaicTextureId
|
||||
}
|
||||
val preparationMs = (System.nanoTime() - preparationStartNs) / 1_000_000L
|
||||
var blackBoxReadSubmitMs = 0L
|
||||
var blackBoxParameterMs = 0L
|
||||
var blackBoxMapWaitMs = 0L
|
||||
var blackBoxUploadSubmitMs = 0L
|
||||
var nativeMs = 0L
|
||||
var denoiseMs = 0L
|
||||
if (applyDefaultDenoise) {
|
||||
lateinit var defaultDenoiseMetadata: RawMetadata
|
||||
lateinit var defaultDenoisePass: MgcFullResolutionDenoise.Pass
|
||||
var tuningSnr = 0f
|
||||
val readTiming = denoiseTransfer.read(
|
||||
workingFloatTexture, width, height, label = "MGC $mode default denoise",
|
||||
beforeMap = {
|
||||
val parameterStartNs = System.nanoTime()
|
||||
defaultDenoiseMetadata = when (mode) {
|
||||
MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT ->
|
||||
spatialOutputNoiseMetadata(denoiseMetadata)
|
||||
MgcSpatialGpuDenoiseMode.SABRE_DEFAULT ->
|
||||
sabreOutputNoiseMetadata(denoiseMetadata)
|
||||
MgcSpatialGpuDenoiseMode.BYPASS_DEFAULT_DENOISE ->
|
||||
error("Bypass mode entered the MGC default-denoise boundary")
|
||||
}
|
||||
defaultDenoisePass = when (mode) {
|
||||
MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT ->
|
||||
MgcFullResolutionDenoise.Pass.SPATIAL_DEFAULT
|
||||
MgcSpatialGpuDenoiseMode.SABRE_DEFAULT ->
|
||||
MgcFullResolutionDenoise.Pass.SABRE_DEFAULT
|
||||
MgcSpatialGpuDenoiseMode.BYPASS_DEFAULT_DENOISE ->
|
||||
error("Bypass mode has no MGC full-resolution pass")
|
||||
}
|
||||
tuningSnr = checkNotNull(metadata.mgcDenoiseTuningSnr?.takeIf {
|
||||
it.isFinite() && it >= 0f
|
||||
}) {
|
||||
"MGC $mode default denoise is missing output-frame SNR"
|
||||
}
|
||||
blackBoxParameterMs =
|
||||
(System.nanoTime() - parameterStartNs) / 1_000_000L
|
||||
},
|
||||
) { mapped ->
|
||||
val nativeStartNs = System.nanoTime()
|
||||
check(
|
||||
MgcFullResolutionDenoise.denoise(
|
||||
rgba16f = mapped,
|
||||
width = width,
|
||||
height = height,
|
||||
globalOriginX = 0,
|
||||
globalOriginY = 0,
|
||||
fullWidth = width,
|
||||
fullHeight = height,
|
||||
outputScale = 1f,
|
||||
metadata = defaultDenoiseMetadata,
|
||||
preparedYuvNoiseModel = demosaicNoiseTransfer.takeIf {
|
||||
mode == MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT
|
||||
},
|
||||
applyLensShadingToDenoiseStrength =
|
||||
mode == MgcSpatialGpuDenoiseMode.SABRE_DEFAULT,
|
||||
tuningSnr = tuningSnr,
|
||||
pass = defaultDenoisePass,
|
||||
lumaStrengthScale = resolvedLumaStrength,
|
||||
chromaStrengthScale = resolvedChromaStrength,
|
||||
)
|
||||
) { "MGC $mode luma/chroma denoise failed" }
|
||||
nativeMs = (System.nanoTime() - nativeStartNs) / 1_000_000L
|
||||
val history = checkNotNull(metadata.denoiseHistory) {
|
||||
"Photon $mode default denoise is missing the merge noise ratios"
|
||||
}
|
||||
blackBoxReadSubmitMs = readTiming.submitMs.toLong()
|
||||
blackBoxMapWaitMs = readTiming.mapMs.toLong()
|
||||
|
||||
val returnStartNs = System.nanoTime()
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
denoiseTransfer.upload(workingFloatTexture, width, height)
|
||||
blackBoxUploadSubmitMs =
|
||||
(System.nanoTime() - returnStartNs) / 1_000_000L
|
||||
val lensShadingSource = when {
|
||||
!outputIncludesLensShading || !hasLensShading -> null
|
||||
isBayerInput -> "demosaic"
|
||||
else -> "merge"
|
||||
}
|
||||
val lensShading = when (lensShadingSource) {
|
||||
"demosaic" -> PhotonLensShading.demosaic(metadata)
|
||||
"merge" -> RawAppliedLensShading.fromCamera2(
|
||||
metadata.lensShadingMap,
|
||||
metadata.lensShadingMapWidth,
|
||||
metadata.lensShadingMapHeight,
|
||||
)?.let(PhotonLensShading::applied)
|
||||
else -> null
|
||||
}
|
||||
val params = checkNotNull(
|
||||
PhotonNoiseModel.build(
|
||||
metadata = metadata,
|
||||
width = width,
|
||||
height = height,
|
||||
originX = 0,
|
||||
originY = 0,
|
||||
fullWidth = width,
|
||||
fullHeight = height,
|
||||
history = history,
|
||||
lumaStrength = resolvedLumaStrength,
|
||||
chromaStrength = resolvedChromaStrength,
|
||||
lensShading = lensShading,
|
||||
),
|
||||
) { "Photon $mode default denoise has no RAW noise profile" }
|
||||
if (PhotonDenoiseDump.enabled) {
|
||||
PhotonDenoiseDump.write(context, "${params.pipeline.name}_DEFAULT", workingFloatTexture,
|
||||
width, height, metadata, params, lensShadingSource)
|
||||
}
|
||||
val denoiseStartNs = System.nanoTime()
|
||||
denoisedTexture = checkNotNull(
|
||||
photonDenoiser.denoise(workingFloatTexture, width, height, params),
|
||||
) { "Photon $mode denoise programs are unavailable" }
|
||||
denoiseMs = (System.nanoTime() - denoiseStartNs) / 1_000_000L
|
||||
outputHistory = params.outputHistory()
|
||||
} else {
|
||||
PLog.i(
|
||||
TAG,
|
||||
@@ -1301,7 +1242,7 @@ class RawDemosaicProcessor {
|
||||
createdExportedTexture = true
|
||||
}
|
||||
renderLinearRawFloatToUint(
|
||||
sourceTextureId = workingFloatTexture,
|
||||
sourceTextureId = if (denoisedTexture != 0) denoisedTexture else workingFloatTexture,
|
||||
targetTextureId = exportedTexture,
|
||||
width = width,
|
||||
height = height,
|
||||
@@ -1322,29 +1263,14 @@ class RawDemosaicProcessor {
|
||||
"luma=$resolvedLumaStrength " +
|
||||
"chroma=$resolvedChromaStrength " +
|
||||
"frames=${metadata.frameCount} " +
|
||||
"readNoise=${metadata.mgcDenoiseReadNoise?.contentToString()} " +
|
||||
"shotNoise=${metadata.mgcDenoiseShotNoise?.contentToString()} " +
|
||||
"strengthMap=${metadata.mgcSpatialStrengthMap?.let {
|
||||
"${it.width}x${it.height}"
|
||||
"history=${outputHistory?.let {
|
||||
"${it.pipeline}:mergeRead=${it.mergeRead},mergeShot=${it.mergeShot}"
|
||||
} ?: "none"} " +
|
||||
"lscIn=$sourcePixelsIncludeLensShadingCorrection " +
|
||||
"lscAppliedToBayer=$applyLensShadingToBayer " +
|
||||
"lscOut=$outputIncludesLensShading " +
|
||||
"demosaicNoiseTransfer=${demosaicNoiseTransfer?.let {
|
||||
"yuvRead=${it.normalizedRead.contentToString()}," +
|
||||
"lumaShot=${it.normalizedLumaShot}," +
|
||||
"chromaShot=${it.normalizedChromaShot}"
|
||||
} ?: if (applyDefaultDenoise) {
|
||||
"analytic-rgb-to-yuv-chroma-envelope"
|
||||
} else {
|
||||
"not-applied"
|
||||
}} " +
|
||||
"prepareSubmitMs=$preparationMs " +
|
||||
"blackBoxReadSubmitMs=$blackBoxReadSubmitMs " +
|
||||
"blackBoxParameterMs=$blackBoxParameterMs " +
|
||||
"blackBoxMapWaitMs=$blackBoxMapWaitMs " +
|
||||
"blackBoxUploadSubmitMs=$blackBoxUploadSubmitMs " +
|
||||
"nativeMs=$nativeMs gpuReturnSubmitMs=$gpuReturnSubmitMs " +
|
||||
"denoiseSubmitMs=$denoiseMs gpuReturnSubmitMs=$gpuReturnSubmitMs " +
|
||||
"cpuPackMs=0 textureReuse=${!createdExportedTexture} " +
|
||||
"result=RGBA16UI_GPU " +
|
||||
"totalMs=${(System.nanoTime() - totalStartNs) / 1_000_000L}",
|
||||
@@ -1359,6 +1285,7 @@ class RawDemosaicProcessor {
|
||||
storage = GpuLinearRgbStorage.RGBA16UI,
|
||||
),
|
||||
pixelsIncludeLensShadingCorrection = outputIncludesLensShading,
|
||||
denoiseHistory = outputHistory,
|
||||
)
|
||||
} catch (error: Exception) {
|
||||
PLog.e(TAG, "Failed to process MGC Spatial GPU output", error)
|
||||
@@ -1366,7 +1293,7 @@ class RawDemosaicProcessor {
|
||||
} finally {
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
|
||||
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1)
|
||||
denoiseTransfer.releaseBuffers()
|
||||
if (denoisedTexture != 0) GLES30.glDeleteTextures(1, intArrayOf(denoisedTexture), 0)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_UNPACK_BUFFER, 0)
|
||||
if (demosaicFramebufferId != 0 && demosaicTextureId != 0) {
|
||||
@@ -1398,8 +1325,7 @@ class RawDemosaicProcessor {
|
||||
|
||||
// Fullscreen passes own their shader programs and lifecycle.
|
||||
private val fullscreenQuad = RawFullscreenQuad()
|
||||
private val chromaDenoiseAlgorithm = ChromaDenoiseAlgorithm(fullscreenQuad)
|
||||
private val denoiseProfileAlgorithm = DenoiseProfileAlgorithm()
|
||||
private val photonDenoiser = PhotonMultiScaleDenoiser()
|
||||
private val profileGainTableAlgorithm = DngPhotonProfileGainTableAlgorithm()
|
||||
private val filmicHighlightReconstructionAlgorithm =
|
||||
DarktableFilmicHighlightReconstructionAlgorithm(fullscreenQuad)
|
||||
@@ -1415,7 +1341,6 @@ class RawDemosaicProcessor {
|
||||
private val srgbPass = RawSrgbPass(fullscreenQuad)
|
||||
private val sharpenPass = RawSharpenPass(fullscreenQuad)
|
||||
private val mgcSharpen = MgcSharpen()
|
||||
private val denoiseTransfer = RawFloatTextureTransfer(RawFloatTextureTransfer.Layout.HALF)
|
||||
/** Final SDR/HDR pixels keep the RGBA16F layout all the way into the Bitmap. */
|
||||
private val outputTransfer = RawFloatTextureTransfer(RawFloatTextureTransfer.Layout.HALF)
|
||||
private var outputTransferAvailable = false
|
||||
@@ -1435,37 +1360,6 @@ class RawDemosaicProcessor {
|
||||
private val legacyHighlightHistogramAlgorithm = RawLegacyHighlightHistogramAlgorithm()
|
||||
private val quadBayerDemosaicAlgorithm = QuadBayerDemosaicAlgorithm()
|
||||
private val vgnDemosaicAlgorithm = VgnDemosaicAlgorithm()
|
||||
private val demosaicNoisePropagationCalibrator = DemosaicNoisePropagationCalibrator(
|
||||
initializePipeline = { cfaPattern ->
|
||||
if (RawMetadata.isQuadBayer(cfaPattern)) {
|
||||
ensureQuadBayerPrograms()
|
||||
} else {
|
||||
ensureVgnPrograms()
|
||||
}
|
||||
},
|
||||
renderDemosaic = { request ->
|
||||
if (RawMetadata.isQuadBayer(request.metadata.cfaPattern)) {
|
||||
runQuadBayerDemosaic(
|
||||
metadata = request.metadata,
|
||||
width = request.width,
|
||||
height = request.height,
|
||||
highlightReconstructionEnabled = false,
|
||||
rawInputTextureId = request.rawTextureId,
|
||||
outputTargetTextureId = request.outputTextureId,
|
||||
)
|
||||
} else {
|
||||
runStandardBayerVgnDemosaic(
|
||||
metadata = request.metadata,
|
||||
width = request.width,
|
||||
height = request.height,
|
||||
highlightReconstructionEnabled = false,
|
||||
rawInputTextureId = request.rawTextureId,
|
||||
linearOutputTargetTextureId = request.linearOutputTextureId,
|
||||
outputTargetTextureId = request.outputTextureId,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
private var rawTextureId = 0
|
||||
private var rawTileTextureWidth = 0
|
||||
@@ -1770,6 +1664,8 @@ class RawDemosaicProcessor {
|
||||
photonSourceToShortGain: Float? = null,
|
||||
photonHdrNetPostExposureEv: Float? = null,
|
||||
photonHdrNetInputExposureEv: Float? = null,
|
||||
appliedLensShading: RawAppliedLensShading? = null,
|
||||
denoiseHistory: RawDenoiseHistory? = null,
|
||||
rawCfaCorrectionMode: String? = null,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
rawOutputScale: Float = 1f,
|
||||
@@ -1823,6 +1719,8 @@ class RawDemosaicProcessor {
|
||||
photonSourceToShortGain = photonSourceToShortGain,
|
||||
photonHdrNetPostExposureEv = photonHdrNetPostExposureEv,
|
||||
photonHdrNetInputExposureEv = photonHdrNetInputExposureEv,
|
||||
appliedLensShading = appliedLensShading,
|
||||
denoiseHistory = denoiseHistory,
|
||||
rawCfaCorrectionMode = rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = rawBlackBorderCrop,
|
||||
rawOutputScale = rawOutputScale,
|
||||
@@ -2040,6 +1938,8 @@ class RawDemosaicProcessor {
|
||||
photonSourceToShortGain: Float? = null,
|
||||
photonHdrNetPostExposureEv: Float? = null,
|
||||
photonHdrNetInputExposureEv: Float? = null,
|
||||
appliedLensShading: RawAppliedLensShading? = null,
|
||||
denoiseHistory: RawDenoiseHistory? = null,
|
||||
onMetadata: ((RawMetadata) -> Unit)? = null
|
||||
): RawHdrRenderResult? = withContext(glDispatcher) {
|
||||
val dngFile = File(dngFilePath)
|
||||
@@ -2097,6 +1997,8 @@ class RawDemosaicProcessor {
|
||||
photonSourceToShortGain = photonSourceToShortGain,
|
||||
photonHdrNetPostExposureEv = photonHdrNetPostExposureEv,
|
||||
photonHdrNetInputExposureEv = photonHdrNetInputExposureEv,
|
||||
appliedLensShading = appliedLensShading,
|
||||
denoiseHistory = denoiseHistory,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to process RAW HDR sources: $dngFilePath", e)
|
||||
@@ -2162,6 +2064,8 @@ class RawDemosaicProcessor {
|
||||
photonSourceToShortGain: Float? = null,
|
||||
photonHdrNetPostExposureEv: Float? = null,
|
||||
photonHdrNetInputExposureEv: Float? = null,
|
||||
appliedLensShading: RawAppliedLensShading? = null,
|
||||
denoiseHistory: RawDenoiseHistory? = null,
|
||||
onMetadata: ((RawMetadata) -> Unit)? = null,
|
||||
): RawHdrRenderResult? = withContext(glDispatcher) {
|
||||
if ((rawData == null && gpuLinearRgbSource == null) ||
|
||||
@@ -2264,6 +2168,8 @@ class RawDemosaicProcessor {
|
||||
photonSourceToShortGain = photonSourceToShortGain,
|
||||
photonHdrNetPostExposureEv = photonHdrNetPostExposureEv,
|
||||
photonHdrNetInputExposureEv = photonHdrNetInputExposureEv,
|
||||
appliedLensShading = appliedLensShading,
|
||||
denoiseHistory = denoiseHistory,
|
||||
defaultCropIsAuthoritative = true,
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
@@ -2325,6 +2231,8 @@ class RawDemosaicProcessor {
|
||||
photonSourceToShortGain: Float? = null,
|
||||
photonHdrNetPostExposureEv: Float? = null,
|
||||
photonHdrNetInputExposureEv: Float? = null,
|
||||
appliedLensShading: RawAppliedLensShading? = null,
|
||||
denoiseHistory: RawDenoiseHistory? = null,
|
||||
rawCfaCorrectionMode: String? = null,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
rawOutputScale: Float = 1f,
|
||||
@@ -2509,11 +2417,6 @@ class RawDemosaicProcessor {
|
||||
// A persisted DNG is a new editing source. Spatial merge state is consumed only
|
||||
// by the pre-write default pass and must never leak into later slider edits.
|
||||
frameCount = 1,
|
||||
mgcDenoiseCorrelation = null,
|
||||
mgcDenoiseReadNoise = null,
|
||||
mgcDenoiseShotNoise = null,
|
||||
mgcSpatialStrengthMap = null,
|
||||
mgcDenoiseTuningSnr = null,
|
||||
mgcSharpenTuningSnr = processLocalMgcSharpenTuningSnr,
|
||||
mgcSharpenAttenuationScale =
|
||||
processLocalMgcSharpenAttenuationScale,
|
||||
@@ -2580,6 +2483,20 @@ class RawDemosaicProcessor {
|
||||
processLocalQualityTuningSensorAreaMm2 ?: it.rawMaxQualityTuningSensorAreaMm2,
|
||||
)
|
||||
}
|
||||
// Gains already in the pixels are independent of the user's LSC preference, which only
|
||||
// governs the gain map still to be applied (docs/photon-multiscale-denoise.md §3.2).
|
||||
if (denoiseHistory != null) {
|
||||
actualMetadata = actualMetadata?.copy(denoiseHistory = denoiseHistory)
|
||||
PLog.i(TAG, "Denoise history restored $denoiseHistory")
|
||||
}
|
||||
if (appliedLensShading != null) {
|
||||
actualMetadata = actualMetadata?.copy(appliedLensShading = appliedLensShading)
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Applied LSC restored ${appliedLensShading.width}x${appliedLensShading.height} " +
|
||||
"hash=${appliedLensShading.hashCode()}",
|
||||
)
|
||||
}
|
||||
val captureProfilePass = sceneExposureRequest != null ||
|
||||
legacyAutoExposureRequest != null || captureProfilePreparationRequested
|
||||
if (!captureProfilePass) {
|
||||
@@ -2908,9 +2825,6 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
return@withContext null
|
||||
}
|
||||
var userAdjustmentNoiseTransfer: DemosaicNoiseTransfer? = null
|
||||
val userAdjustmentDenoiseEnabled =
|
||||
(denoiseValue ?: 0f) > 0f || (chromaDenoiseValue ?: 0f) > 0f
|
||||
if (rawRenderTiles.isEmpty()) {
|
||||
when {
|
||||
useHalfResolutionMeteringDemosaic -> setupFullResFramebuffer(
|
||||
@@ -3217,13 +3131,6 @@ class RawDemosaicProcessor {
|
||||
"Reusing capture-profile full-resolution demosaic: " +
|
||||
"${demosaicWidth}x$demosaicHeight texture=$demosaicTextureId",
|
||||
)
|
||||
if (userAdjustmentDenoiseEnabled) {
|
||||
userAdjustmentNoiseTransfer =
|
||||
demosaicNoisePropagationCalibrator.prepareUserAdjustment(
|
||||
actualMetadata,
|
||||
demosaicCalculationWbGains(actualMetadata),
|
||||
)
|
||||
}
|
||||
} else if (useHalfResolutionMeteringDemosaic) {
|
||||
runHalfResolutionMeteringDemosaic(
|
||||
metadata = actualMetadata,
|
||||
@@ -3256,13 +3163,6 @@ class RawDemosaicProcessor {
|
||||
// darktable feeds Filmic after the raw highlight reconstruction module;
|
||||
// keep the raw-domain repair enabled before Filmic HR.
|
||||
val rawDomainHighlightReconstructionEnabled = true
|
||||
if (!captureProfilePreparationRequested && userAdjustmentDenoiseEnabled) {
|
||||
userAdjustmentNoiseTransfer =
|
||||
demosaicNoisePropagationCalibrator.prepareUserAdjustment(
|
||||
actualMetadata,
|
||||
demosaicCalculationWbGains(actualMetadata),
|
||||
)
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAW fused input layout=CFA frameCount=${actualMetadata.frameCount} " +
|
||||
@@ -3896,35 +3796,19 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
}
|
||||
|
||||
val denoiseProfileTextureId = renderMgcUserAdjustmentDenoise(
|
||||
val denoiseProfileTextureId = renderPhotonUserAdjustmentDenoise(
|
||||
context = context.applicationContext,
|
||||
sourceTextureId = demosaicTextureId,
|
||||
width = actualWidth,
|
||||
height = actualHeight,
|
||||
metadata = actualMetadata,
|
||||
demosaicNoiseTransfer = userAdjustmentNoiseTransfer,
|
||||
denoiseValue = denoiseValue,
|
||||
chromaDenoiseValue = chromaDenoiseValue,
|
||||
globalOriginX = 0,
|
||||
globalOriginY = 0,
|
||||
fullImageWidth = actualWidth,
|
||||
fullImageHeight = actualHeight,
|
||||
) ?: run {
|
||||
val fallbackChromaTextureId = renderDefaultChromaDenoise(
|
||||
sourceTextureId = demosaicTextureId,
|
||||
width = actualWidth,
|
||||
height = actualHeight,
|
||||
metadata = actualMetadata,
|
||||
chromaDenoiseValue = chromaDenoiseValue,
|
||||
)
|
||||
renderDenoiseProfilePass(
|
||||
sourceTextureId = fallbackChromaTextureId,
|
||||
width = actualWidth,
|
||||
height = actualHeight,
|
||||
metadata = actualMetadata,
|
||||
denoiseValue = denoiseValue,
|
||||
)
|
||||
}
|
||||
)
|
||||
// AdobeCurve keeps BaselineExposure for the DNG SDK exposure ramp. HNCS consumes
|
||||
// it through ColorCorrectAll's camera-domain inputEV; other linear engines retain
|
||||
// the exact post-matrix 2^EV gain.
|
||||
@@ -4483,20 +4367,7 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
|
||||
var completed = false
|
||||
var userAdjustmentNoiseTransfer: DemosaicNoiseTransfer? = null
|
||||
val userAdjustmentDenoiseEnabled =
|
||||
(config.denoiseValue ?: 0f) > 0f || (config.chromaDenoiseValue ?: 0f) > 0f
|
||||
try {
|
||||
if (userAdjustmentDenoiseEnabled && config.samplesPerPixel == 1) {
|
||||
// The calibration atlas runs once. Do not retain its 1024x256 intermediates in
|
||||
// the full-size tile pool for the remainder of this render.
|
||||
vgnDemosaicAlgorithm.setTileTexturePoolingEnabled(false)
|
||||
userAdjustmentNoiseTransfer =
|
||||
demosaicNoisePropagationCalibrator.prepareUserAdjustment(
|
||||
config.metadata,
|
||||
demosaicCalculationWbGains(config.metadata),
|
||||
)
|
||||
}
|
||||
vgnDemosaicAlgorithm.setTileTexturePoolingEnabled(true)
|
||||
// The refine chain derives its strength from this rate, exactly like the
|
||||
// untiled path; the tiled path owns its own scope.
|
||||
@@ -4561,35 +4432,19 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
val denoisedTextureId = renderMgcUserAdjustmentDenoise(
|
||||
val denoisedTextureId = renderPhotonUserAdjustmentDenoise(
|
||||
context = config.context,
|
||||
sourceTextureId = demosaicTextureId,
|
||||
width = workWidth,
|
||||
height = workHeight,
|
||||
metadata = config.metadata,
|
||||
demosaicNoiseTransfer = userAdjustmentNoiseTransfer,
|
||||
denoiseValue = config.denoiseValue,
|
||||
chromaDenoiseValue = config.chromaDenoiseValue,
|
||||
globalOriginX = working.left,
|
||||
globalOriginY = working.top,
|
||||
fullImageWidth = config.fullWidth,
|
||||
fullImageHeight = config.fullHeight,
|
||||
) ?: run {
|
||||
val fallbackChromaTextureId = renderDefaultChromaDenoise(
|
||||
sourceTextureId = demosaicTextureId,
|
||||
width = workWidth,
|
||||
height = workHeight,
|
||||
metadata = config.metadata,
|
||||
chromaDenoiseValue = config.chromaDenoiseValue,
|
||||
)
|
||||
renderDenoiseProfilePass(
|
||||
sourceTextureId = fallbackChromaTextureId,
|
||||
width = workWidth,
|
||||
height = workHeight,
|
||||
metadata = config.metadata,
|
||||
denoiseValue = config.denoiseValue,
|
||||
)
|
||||
}
|
||||
)
|
||||
if (usesGuidedToneUpsample(config.outputGeometry, config.colorEngine)) {
|
||||
val resolution = config.outputGeometry.mgcFinishResolution
|
||||
check(working.left % resolution.processingPeriod == 0 &&
|
||||
@@ -5434,195 +5289,82 @@ class RawDemosaicProcessor {
|
||||
gfHeight = 0
|
||||
}
|
||||
|
||||
private fun renderDefaultChromaDenoise(
|
||||
sourceTextureId: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
metadata: RawMetadata,
|
||||
chromaDenoiseValue: Float?,
|
||||
): Int {
|
||||
val strength = DenoiseStrength.clamp(chromaDenoiseValue)
|
||||
if (strength <= 0f || width * height < 2) return sourceTextureId
|
||||
if (linearOutputFramebufferId == 0 || linearOutputTextureId == 0) {
|
||||
PLog.w(TAG, "RAW chroma denoise target is unavailable")
|
||||
return sourceTextureId
|
||||
}
|
||||
|
||||
setupNLMFramebuffers(width, height, setupLegacyAccumulator = false)
|
||||
val profileGain =
|
||||
(metadata.iso / 100f * metadata.postRawSensitivityBoost).coerceAtLeast(1f)
|
||||
val noise = resolveChromaDenoiseNoiseModel(metadata, profileGain)
|
||||
val output = chromaDenoiseAlgorithm.execute(
|
||||
ChromaDenoiseAlgorithm.Input(
|
||||
sourceTextureId = sourceTextureId,
|
||||
guideFramebufferId = gfFboId[0],
|
||||
guideTextureId = gfTexId[0],
|
||||
outputFramebufferId = linearOutputFramebufferId,
|
||||
outputTextureId = linearOutputTextureId,
|
||||
width = width,
|
||||
height = height,
|
||||
strength = strength,
|
||||
cameraRgbInput = true,
|
||||
noiseModel = ChromaDenoiseAlgorithm.NoiseModel(
|
||||
redSlope = noise.redSlope,
|
||||
redOffset = noise.redOffset,
|
||||
greenSlope = noise.greenSlope,
|
||||
greenOffset = noise.greenOffset,
|
||||
blueSlope = noise.blueSlope,
|
||||
blueOffset = noise.blueOffset,
|
||||
),
|
||||
),
|
||||
) ?: return sourceTextureId
|
||||
return output.textureId
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the extracted non-AI MGC chroma pyramid and/or Pecan luma stage.
|
||||
*
|
||||
* Camera RGB is already lens-shading corrected by demosaic. The LSC grid is
|
||||
* consumed only by ComputeDenoiseStrengthMaps and is never multiplied into
|
||||
* pixels again. Chroma and luma retain independent user switches.
|
||||
* The Photon multiscale denoiser on the user's luma / chroma strengths
|
||||
* (docs/photon-multiscale-denoise.md §8, §10.3). [sourceTextureId] is camera RGB with the
|
||||
* metadata's applied or demosaic LSC gains; the result is in gfTexId[1]. Without a RAW noise
|
||||
* profile the source is returned unchanged.
|
||||
*/
|
||||
private fun renderMgcUserAdjustmentDenoise(
|
||||
private fun renderPhotonUserAdjustmentDenoise(
|
||||
context: Context,
|
||||
sourceTextureId: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
metadata: RawMetadata,
|
||||
demosaicNoiseTransfer: DemosaicNoiseTransfer?,
|
||||
denoiseValue: Float?,
|
||||
chromaDenoiseValue: Float?,
|
||||
globalOriginX: Int,
|
||||
globalOriginY: Int,
|
||||
fullImageWidth: Int,
|
||||
fullImageHeight: Int,
|
||||
): Int? {
|
||||
): Int {
|
||||
val lumaStrength = DenoiseStrength.clamp(denoiseValue)
|
||||
val chromaStrength = DenoiseStrength.clamp(chromaDenoiseValue)
|
||||
val lumaEnabled = lumaStrength > 0f
|
||||
val chromaEnabled = chromaStrength > 0f
|
||||
val enabled = lumaEnabled || chromaEnabled
|
||||
if (!enabled || width * height < 2) {
|
||||
if ((lumaStrength <= 0f && chromaStrength <= 0f) || width * height < 2) return sourceTextureId
|
||||
check(photonDenoiser.initialize()) { "Photon denoise programs are unavailable" }
|
||||
val appliedLensShading = metadata.appliedLensShading
|
||||
val lensShadingSource = when {
|
||||
appliedLensShading != null -> "merge"
|
||||
hasValidLensShadingMap(metadata) -> "demosaic"
|
||||
else -> null
|
||||
}
|
||||
val lensShading = when (lensShadingSource) {
|
||||
"merge" -> PhotonLensShading.applied(checkNotNull(appliedLensShading))
|
||||
"demosaic" -> PhotonLensShading.demosaic(metadata)
|
||||
else -> null
|
||||
}
|
||||
val params = PhotonNoiseModel.build(
|
||||
metadata = metadata,
|
||||
width = width,
|
||||
height = height,
|
||||
originX = globalOriginX,
|
||||
originY = globalOriginY,
|
||||
fullWidth = fullImageWidth,
|
||||
fullHeight = fullImageHeight,
|
||||
history = PhotonNoiseModel.historyOf(metadata),
|
||||
lumaStrength = lumaStrength,
|
||||
chromaStrength = chromaStrength,
|
||||
lensShading = lensShading,
|
||||
) ?: run {
|
||||
PLog.w(TAG, "Photon denoise skipped: no RAW noise profile layout=${metadata.noiseProfileLayout}")
|
||||
return sourceTextureId
|
||||
}
|
||||
if (!MgcFullResolutionDenoise.ensureInitialized(context)) {
|
||||
PLog.w(TAG, "MGC RunFullResolutionDenoise is not initialized")
|
||||
return null
|
||||
if (PhotonDenoiseDump.enabled) {
|
||||
PhotonDenoiseDump.write(context, "${params.pipeline.name}_USER", sourceTextureId, width, height,
|
||||
metadata, params, lensShadingSource)
|
||||
}
|
||||
setupNLMFramebuffers(width, height, setupLegacyAccumulator = false)
|
||||
val startNs = System.nanoTime()
|
||||
val denoised = checkNotNull(photonDenoiser.denoise(sourceTextureId, width, height, params)) {
|
||||
"Photon denoise programs are unavailable"
|
||||
}
|
||||
setupNLMFramebuffers(
|
||||
width,
|
||||
height,
|
||||
setupLegacyAccumulator = false,
|
||||
)
|
||||
|
||||
try {
|
||||
denoiseTransfer.prepare(width, height)
|
||||
renderPassthroughToTexture(sourceTextureId, width, height, gfFboId[0])
|
||||
var nativeMs = 0L
|
||||
var succeeded = false
|
||||
val timing = denoiseTransfer.read(
|
||||
gfTexId[0], width, height, label = "MGC USER_ADJUSTMENT denoise",
|
||||
) { readback ->
|
||||
val nativeStartNs = System.nanoTime()
|
||||
// Ordinary CFA RAW sources receive a measured single-frame SNR in withMgcRenderTuning().
|
||||
// Keep the legacy coordinate only for editing sources whose layout/noise profile cannot
|
||||
// produce that physical measurement; Spatial/Sabre defaults never enter this fallback.
|
||||
val tuningSnr = metadata.mgcDenoiseTuningSnr ?: (
|
||||
metadata.iso.toFloat() / 100.0f *
|
||||
metadata.postRawSensitivityBoost
|
||||
).coerceAtLeast(0.001f).also { fallbackSnr ->
|
||||
PLog.w(
|
||||
TAG,
|
||||
"MGC USER_ADJUSTMENT uses legacy tuning coordinate: " +
|
||||
"layout=${metadata.noiseProfileLayout} iso=${metadata.iso} " +
|
||||
"postRawBoost=${metadata.postRawSensitivityBoost} snr=$fallbackSnr",
|
||||
)
|
||||
}
|
||||
succeeded = MgcFullResolutionDenoise.denoise(
|
||||
rgba16f = readback,
|
||||
width = width,
|
||||
height = height,
|
||||
globalOriginX = globalOriginX,
|
||||
globalOriginY = globalOriginY,
|
||||
fullWidth = fullImageWidth,
|
||||
fullHeight = fullImageHeight,
|
||||
metadata = metadata,
|
||||
preparedYuvNoiseModel = demosaicNoiseTransfer,
|
||||
applyLensShadingToDenoiseStrength = hasValidLensShadingMap(metadata),
|
||||
tuningSnr = tuningSnr,
|
||||
pass = MgcFullResolutionDenoise.Pass.USER_ADJUSTMENT,
|
||||
lumaStrengthScale = lumaStrength,
|
||||
chromaStrengthScale = chromaStrength,
|
||||
)
|
||||
nativeMs = (System.nanoTime() - nativeStartNs) / 1_000_000L
|
||||
}
|
||||
if (!succeeded) return null
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
denoiseTransfer.upload(gfTexId[0], width, height)
|
||||
renderPassthroughToTexture(
|
||||
gfTexId[0],
|
||||
width,
|
||||
height,
|
||||
gfFboId[1],
|
||||
)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
checkGlError("MGC denoise output RGB")
|
||||
PLog.d(
|
||||
TAG,
|
||||
"MGC static denoise timing size=${width}x$height " +
|
||||
"pass=USER_ADJUSTMENT " +
|
||||
"luma=$lumaEnabled($lumaStrength) " +
|
||||
"chroma=$chromaEnabled($chromaStrength) " +
|
||||
"noiseTransfer=${demosaicNoiseTransfer?.let {
|
||||
if (RawMetadata.isQuadBayer(metadata.cfaPattern)) {
|
||||
"QUAD_BAYER"
|
||||
} else {
|
||||
"STANDARD_BAYER_VGN"
|
||||
}
|
||||
} ?: "identity"} " +
|
||||
"lscStrength=${lensShadingLogString(metadata)} " +
|
||||
"transferSubmitMs=${timing.submitMs} mapMs=${timing.mapMs} " +
|
||||
"nativeMs=$nativeMs",
|
||||
)
|
||||
return gfTexId[1]
|
||||
renderPassthroughToTexture(denoised, width, height, gfFboId[1])
|
||||
} finally {
|
||||
// Deletion waits for the queued upload that sources this buffer.
|
||||
denoiseTransfer.releaseBuffers()
|
||||
GLES30.glDeleteTextures(1, intArrayOf(denoised), 0)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染 darktable denoiseprofile NLM 降噪。
|
||||
*
|
||||
* 管线: 未白平衡 camera RGB → variance-stabilizing transform → NLM accumulate
|
||||
* → inverse transform → 未白平衡 camera RGB (gfFboId[1])。
|
||||
*/
|
||||
private fun renderDenoiseProfilePass(
|
||||
sourceTextureId: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
metadata: RawMetadata,
|
||||
denoiseValue: Float?,
|
||||
): Int {
|
||||
val strength = DenoiseStrength.clamp(denoiseValue)
|
||||
if (strength <= 0f || width * height < 2) return sourceTextureId
|
||||
val profileGain =
|
||||
(metadata.iso / 100f * metadata.postRawSensitivityBoost).coerceAtLeast(1f)
|
||||
val (noiseSlope, noiseOffset) =
|
||||
resolveDenoiseProfileNoiseModel(metadata, profileGain)
|
||||
val wb = demosaicCalculationWbGains(metadata)
|
||||
return denoiseProfileAlgorithm.execute(
|
||||
DenoiseProfileAlgorithm.Input(
|
||||
sourceTextureId = sourceTextureId,
|
||||
width = width,
|
||||
height = height,
|
||||
strength = strength,
|
||||
noiseSlope = noiseSlope,
|
||||
noiseOffset = noiseOffset,
|
||||
adaptiveWhiteBalance = floatArrayOf(wb[0], 1f, wb[3]),
|
||||
),
|
||||
)?.textureId ?: sourceTextureId
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
checkGlError("Photon denoise output RGB")
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Photon denoise size=${width}x$height pipeline=${params.pipeline} n=${params.noiseCoordinate} " +
|
||||
"levels=${params.levels} merge=${params.mergeRead},${params.mergeShot} " +
|
||||
"residual0=${params.residual[0].contentToString()} " +
|
||||
"luma=$lumaStrength chroma=$chromaStrength lsc=${lensShadingSource ?: "none"} " +
|
||||
"submitMs=${(System.nanoTime() - startNs) / 1_000_000L}",
|
||||
)
|
||||
return gfTexId[1]
|
||||
}
|
||||
|
||||
private fun renderPassthroughToTexture(
|
||||
@@ -6288,61 +6030,37 @@ class RawDemosaicProcessor {
|
||||
|
||||
|
||||
/**
|
||||
* Exposes Spatial AOT's already propagated output model as the noise profile of the one
|
||||
* merged Bayer image. frameCount is one here only to prevent VGN's single-frame threshold
|
||||
* resolver from dividing the AOT coefficients by the burst count a second time.
|
||||
* Noise profile of the one merged Bayer image for the demosaic's thresholds: the reference
|
||||
* frame's RAW profile scaled by the merge's §2.2 variance ratios
|
||||
* (docs/photon-multiscale-denoise.md). frameCount is one so the demosaic's single-frame
|
||||
* resolver does not divide by the burst count a second time.
|
||||
*/
|
||||
private fun spatialOutputNoiseMetadata(metadata: RawMetadata): RawMetadata {
|
||||
val read = checkNotNull(metadata.mgcDenoiseReadNoise) {
|
||||
"Spatial AOT output read coefficients are unavailable"
|
||||
val history = checkNotNull(metadata.denoiseHistory) {
|
||||
"Spatial merge noise ratios are unavailable"
|
||||
}
|
||||
val shot = checkNotNull(metadata.mgcDenoiseShotNoise) {
|
||||
"Spatial AOT output shot coefficients are unavailable"
|
||||
val noise = checkNotNull(PhotonNoiseModel.profileNoise(metadata)) {
|
||||
"Spatial merge has no RAW noise profile"
|
||||
}
|
||||
check(
|
||||
read.size == 3 && shot.size == 3 &&
|
||||
read.all { it.isFinite() && it >= 0f } &&
|
||||
shot.all { it.isFinite() && it >= 0f } &&
|
||||
(read.any { it > 0f } || shot.any { it > 0f }),
|
||||
) { "Spatial AOT output noise coefficients are malformed" }
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial default denoise noise source=spatial-aot " +
|
||||
"captureFrames=${metadata.frameCount} " +
|
||||
"read=${read.contentToString()} shot=${shot.contentToString()}",
|
||||
"Spatial demosaic noise source=profile-merge-ratio captureFrames=${metadata.frameCount} " +
|
||||
"mergeRead=${history.mergeRead} mergeShot=${history.mergeShot}",
|
||||
)
|
||||
return metadata.copy(
|
||||
frameCount = 1,
|
||||
channelNoiseProfile = floatArrayOf(
|
||||
shot[0], read[0],
|
||||
shot[1], read[1],
|
||||
shot[2], read[2],
|
||||
),
|
||||
channelNoiseProfile = FloatArray(6) { index ->
|
||||
val channel = index / 2
|
||||
if (index % 2 == 0) {
|
||||
noise.shot[channel] * history.mergeShot
|
||||
} else {
|
||||
noise.read[channel] * history.mergeRead
|
||||
}
|
||||
},
|
||||
noiseProfileLayout = RawNoiseProfileLayout.DNG_RGB,
|
||||
)
|
||||
}
|
||||
|
||||
/** Consume the classic Sabre merged model once, without reference-model or frame-count scaling. */
|
||||
private fun sabreOutputNoiseMetadata(metadata: RawMetadata): RawMetadata {
|
||||
val read = checkNotNull(metadata.mgcDenoiseReadNoise)
|
||||
val shot = checkNotNull(metadata.mgcDenoiseShotNoise)
|
||||
val correlation = checkNotNull(metadata.mgcDenoiseCorrelation)
|
||||
check(read.size == 3 && shot.size == 3 && correlation.size == 128)
|
||||
check(read.all { it.isFinite() && it >= 0f } &&
|
||||
shot.all { it.isFinite() && it >= 0f } &&
|
||||
correlation.all { it.isFinite() && it >= 0f })
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Sabre default denoise noise source=classic-merged-model " +
|
||||
"captureFrames=${metadata.frameCount} " +
|
||||
"read=${read.contentToString()} shot=${shot.contentToString()}",
|
||||
)
|
||||
return metadata.copy(
|
||||
frameCount = 1,
|
||||
mgcSpatialStrengthMap = null,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapses each standard Bayer 2x2 cell to one camera-RGB texel for capture-side exposure
|
||||
* matching. The result stays in the same un-white-balanced, lens-shading-corrected domain as
|
||||
@@ -7919,19 +7637,14 @@ class RawDemosaicProcessor {
|
||||
) { "RAW HDR reference pass failed" }
|
||||
}
|
||||
|
||||
/** Share one native RAW measurement; merged captures already carry reference-frame SNR. */
|
||||
/** MGC sharpen tuning SNR from one native RAW measurement; merged captures carry the reference frame's. */
|
||||
private fun RawMetadata.withMgcRenderTuning(
|
||||
rawData: ByteBuffer?,
|
||||
rowStride: Int,
|
||||
samplesPerPixel: Int,
|
||||
): RawMetadata {
|
||||
val needsSingleFrameDenoiseSnr =
|
||||
samplesPerPixel == 1 && frameCount == 1 && mgcDenoiseTuningSnr == null
|
||||
// Guided reconstruction is still required when the sharpening slider is zero.
|
||||
val needsSharpenSnr = mgcSharpenTuningSnr == null
|
||||
if (!needsSingleFrameDenoiseSnr && !needsSharpenSnr) {
|
||||
return this
|
||||
}
|
||||
if (mgcSharpenTuningSnr != null) return this
|
||||
val signalStartNs = System.nanoTime()
|
||||
val measuredSignal = rawData?.let { estimateMgcReferenceSignal(
|
||||
rawData = it,
|
||||
@@ -7976,19 +7689,10 @@ class RawDemosaicProcessor {
|
||||
TAG,
|
||||
"MGC RAW render tuning signal=$signal snr=$snr " +
|
||||
"greenShot=$greenShot greenRead=$greenRead " +
|
||||
"singleFrameDenoise=$needsSingleFrameDenoiseSnr " +
|
||||
"sharpen=$needsSharpenSnr " +
|
||||
"signalSource=${if (measuredSignal != null) "NATIVE_OMP" else "MGC_MISSING_MEAN"} " +
|
||||
"signalMs=$signalElapsedMs",
|
||||
)
|
||||
return copy(
|
||||
mgcSharpenTuningSnr = if (needsSharpenSnr) snr else mgcSharpenTuningSnr,
|
||||
mgcDenoiseTuningSnr = if (needsSingleFrameDenoiseSnr && measuredSignal != null && snr > 0f) {
|
||||
snr
|
||||
} else {
|
||||
mgcDenoiseTuningSnr
|
||||
},
|
||||
)
|
||||
return copy(mgcSharpenTuningSnr = snr)
|
||||
}
|
||||
|
||||
private fun RawMetadata.estimateMgcReferenceSignal(
|
||||
@@ -9425,14 +9129,11 @@ class RawDemosaicProcessor {
|
||||
srgbPass.release()
|
||||
sharpenPass.release()
|
||||
mgcSharpen.release()
|
||||
denoiseTransfer.release()
|
||||
raisrTransfer.release()
|
||||
outputPass.release()
|
||||
hdrReferencePass.release()
|
||||
chromaDenoiseAlgorithm.release()
|
||||
filmicHighlightReconstructionAlgorithm.release()
|
||||
|
||||
demosaicNoisePropagationCalibrator.release()
|
||||
vgnDemosaicAlgorithm.release()
|
||||
quadBayerDemosaicAlgorithm.release()
|
||||
profileGainTableAlgorithm.release()
|
||||
@@ -9444,7 +9145,7 @@ class RawDemosaicProcessor {
|
||||
linearUintToFloatPass.release()
|
||||
linearFloatToUintPass.release()
|
||||
linearRgbExpandPass.release()
|
||||
denoiseProfileAlgorithm.release()
|
||||
photonDenoiser.release()
|
||||
releaseDenoiseProfileFramebuffers()
|
||||
|
||||
if (exportedStackTextureIds.isNotEmpty()) {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
/** Pipelines with separate denoise tuning tables (docs/photon-multiscale-denoise.md §5). */
|
||||
enum class RawDenoisePipeline { VGN, QUAD, SABRE, SPATIAL, BITMAP }
|
||||
|
||||
/**
|
||||
* Noise state of pixels produced by a merge and/or an earlier denoise
|
||||
* (docs/photon-multiscale-denoise.md §2.2, §2.4).
|
||||
*
|
||||
* [pipeline] is the pipeline that produced the pixels, which selects the tuning table.
|
||||
* [mergeRead] / [mergeShot] scale the reference frame's read / shot coefficients to the merged
|
||||
* pixels (§2.2, including the merge's output exposure). [residual] holds the residual variance
|
||||
* ratio t² per pyramid level as (Y, Cb, Cr); null means the pixels have not been denoised.
|
||||
* Levels beyond [residual] were left untouched and keep ratio 1.
|
||||
*/
|
||||
data class RawDenoiseHistory(
|
||||
val pipeline: RawDenoisePipeline,
|
||||
val mergeRead: Float,
|
||||
val mergeShot: Float,
|
||||
val residual: List<FloatArray>? = null,
|
||||
) {
|
||||
val isValid: Boolean
|
||||
get() = mergeRead.isFinite() && mergeRead > 0f && mergeShot.isFinite() && mergeShot > 0f &&
|
||||
residual?.all { level -> level.size == 3 && level.all { it.isFinite() && it in 0f..1f } } != false
|
||||
|
||||
/** t² of [level] as (Y, Cb, Cr). */
|
||||
fun residualAt(level: Int): FloatArray = residual?.getOrNull(level)?.copyOf() ?: floatArrayOf(1f, 1f, 1f)
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (other !is RawDenoiseHistory) return false
|
||||
if (pipeline != other.pipeline || mergeRead != other.mergeRead || mergeShot != other.mergeShot) return false
|
||||
val a = residual
|
||||
val b = other.residual
|
||||
if (a == null || b == null) return a == b
|
||||
return a.size == b.size && a.indices.all { a[it].contentEquals(b[it]) }
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
var result = pipeline.hashCode()
|
||||
result = 31 * result + mergeRead.hashCode()
|
||||
result = 31 * result + mergeShot.hashCode()
|
||||
result = 31 * result + (residual?.fold(0) { acc, level -> 31 * acc + level.contentHashCode() } ?: 0)
|
||||
return result
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** A single, not yet denoised frame of [pipeline]. */
|
||||
fun singleFrame(pipeline: RawDenoisePipeline) = RawDenoiseHistory(pipeline, 1f, 1f)
|
||||
}
|
||||
}
|
||||
|
||||
/** Gallery-metadata persistence of [RawDenoiseHistory], alongside RawAppliedLensShadingMetadata. */
|
||||
internal object RawDenoiseHistoryMetadata {
|
||||
private const val PIPELINE_PROPERTY = "photonDenoisePipeline"
|
||||
private const val MERGE_PROPERTY = "photonDenoiseMerge"
|
||||
private const val RESIDUAL_PROPERTY = "photonDenoiseResidual"
|
||||
private const val CONTRACT_PROPERTY = "photonDenoiseHistoryContract"
|
||||
private const val CURRENT_CONTRACT = "pipeline_merge_read_shot_residual_level_y_cb_cr_v1"
|
||||
|
||||
fun write(properties: Map<String, String>, value: RawDenoiseHistory?): Map<String, String> {
|
||||
val out = properties.toMutableMap()
|
||||
out.remove(PIPELINE_PROPERTY)
|
||||
out.remove(MERGE_PROPERTY)
|
||||
out.remove(RESIDUAL_PROPERTY)
|
||||
out.remove(CONTRACT_PROPERTY)
|
||||
if (value == null) return out
|
||||
require(value.isValid) { "Denoise history is malformed" }
|
||||
out[PIPELINE_PROPERTY] = value.pipeline.name
|
||||
out[MERGE_PROPERTY] = "${value.mergeRead},${value.mergeShot}"
|
||||
value.residual?.let { levels ->
|
||||
out[RESIDUAL_PROPERTY] = levels.joinToString(";") { it.joinToString(",") }
|
||||
}
|
||||
out[CONTRACT_PROPERTY] = CURRENT_CONTRACT
|
||||
return out
|
||||
}
|
||||
|
||||
fun read(properties: Map<String, String>): RawDenoiseHistory? {
|
||||
if (properties[CONTRACT_PROPERTY] != CURRENT_CONTRACT) return null
|
||||
val pipeline = RawDenoisePipeline.entries.firstOrNull { it.name == properties[PIPELINE_PROPERTY] }
|
||||
?: return null
|
||||
val merge = properties[MERGE_PROPERTY]?.split(',')?.mapNotNull(String::toFloatOrNull)
|
||||
?.takeIf { it.size == 2 } ?: return null
|
||||
val residual = properties[RESIDUAL_PROPERTY]?.let { encoded ->
|
||||
encoded.split(';').map { level ->
|
||||
level.split(',').mapNotNull(String::toFloatOrNull).toFloatArray()
|
||||
}
|
||||
}
|
||||
return RawDenoiseHistory(pipeline, merge[0], merge[1], residual).takeIf { it.isValid }
|
||||
}
|
||||
}
|
||||
@@ -149,6 +149,18 @@ data class RawMetadata(
|
||||
*/
|
||||
val lensShadingMapGrid: FloatArray? = null,
|
||||
|
||||
/**
|
||||
* 已乘入像素的 LSC 增益(合成时施加),降噪入口除去、出口乘回。
|
||||
* 与待施加的 [lensShadingMap] 相互独立,见 docs/photon-multiscale-denoise.md §3.2。
|
||||
*/
|
||||
val appliedLensShading: RawAppliedLensShading? = null,
|
||||
|
||||
/**
|
||||
* 合成方差比与已降噪的残余比,见 docs/photon-multiscale-denoise.md §2.2、§2.4。
|
||||
* null 表示未合成、未降噪的单帧。
|
||||
*/
|
||||
val denoiseHistory: RawDenoiseHistory? = null,
|
||||
|
||||
/**
|
||||
* 数字增益 (Post RAW Boost)
|
||||
*/
|
||||
@@ -181,19 +193,6 @@ data class RawMetadata(
|
||||
val sensorPixelArrayWidth: Int = 0,
|
||||
val sensorPixelArrayHeight: Int = 0,
|
||||
val frameCount: Int = 1,
|
||||
/**
|
||||
* MGC's normalized 128-bin power-correlation spectrum after the selected MGC merge branch.
|
||||
* Null means either a single uncorrelated source or an unsupported propagated model.
|
||||
*/
|
||||
val mgcDenoiseCorrelation: FloatArray? = null,
|
||||
/** Process-local normalized camera-RGB read variance emitted by the selected MGC merge branch. */
|
||||
val mgcDenoiseReadNoise: FloatArray? = null,
|
||||
/** Process-local normalized camera-RGB shot coefficient emitted by the selected MGC merge branch. */
|
||||
val mgcDenoiseShotNoise: FloatArray? = null,
|
||||
/** Exact process-local Q8 Spatial variance multiplier; never serialized into DNG. */
|
||||
val mgcSpatialStrengthMap: MgcSpatialStrengthMap? = null,
|
||||
/** Merged output-frame SNR used by MGC FinishRaw to select luma/chroma tuning. */
|
||||
val mgcDenoiseTuningSnr: Float? = null,
|
||||
/** Reference-frame SNR for original MGC sharpen curve selection; not the merged SNR. */
|
||||
val mgcSharpenTuningSnr: Float? = null,
|
||||
/** MGC-derived attenuation applied to the final sharpen kernel. */
|
||||
@@ -1171,6 +1170,8 @@ data class RawMetadata(
|
||||
} else if (other.camera2ColorCorrectionTransform != null) return false
|
||||
if (camera2ColorCorrectionMode != other.camera2ColorCorrectionMode) return false
|
||||
if (!cameraWhite.contentEquals(other.cameraWhite)) return false
|
||||
if (appliedLensShading != other.appliedLensShading) return false
|
||||
if (denoiseHistory != other.denoiseHistory) return false
|
||||
if (baselineExposure != other.baselineExposure) return false
|
||||
if (shadowScale != other.shadowScale) return false
|
||||
if (iso != other.iso) return false
|
||||
@@ -1180,20 +1181,6 @@ data class RawMetadata(
|
||||
if (frameCount != other.frameCount) return false
|
||||
if (!channelNoiseProfile.contentEquals(other.channelNoiseProfile)) return false
|
||||
if (noiseProfileLayout != other.noiseProfileLayout) return false
|
||||
if (mgcDenoiseCorrelation != null) {
|
||||
if (other.mgcDenoiseCorrelation == null) return false
|
||||
if (!mgcDenoiseCorrelation.contentEquals(other.mgcDenoiseCorrelation)) return false
|
||||
} else if (other.mgcDenoiseCorrelation != null) return false
|
||||
if (mgcDenoiseReadNoise != null) {
|
||||
if (other.mgcDenoiseReadNoise == null) return false
|
||||
if (!mgcDenoiseReadNoise.contentEquals(other.mgcDenoiseReadNoise)) return false
|
||||
} else if (other.mgcDenoiseReadNoise != null) return false
|
||||
if (mgcDenoiseShotNoise != null) {
|
||||
if (other.mgcDenoiseShotNoise == null) return false
|
||||
if (!mgcDenoiseShotNoise.contentEquals(other.mgcDenoiseShotNoise)) return false
|
||||
} else if (other.mgcDenoiseShotNoise != null) return false
|
||||
if (mgcSpatialStrengthMap != other.mgcSpatialStrengthMap) return false
|
||||
if (mgcDenoiseTuningSnr != other.mgcDenoiseTuningSnr) return false
|
||||
if (mgcSharpenTuningSnr != other.mgcSharpenTuningSnr) return false
|
||||
if (mgcSharpenAttenuationScale != other.mgcSharpenAttenuationScale) return false
|
||||
if (rawMaxQualityTuningEnabled != other.rawMaxQualityTuningEnabled) return false
|
||||
@@ -1219,6 +1206,8 @@ data class RawMetadata(
|
||||
result = 31 * result + lensShadingMapWidth
|
||||
result = 31 * result + lensShadingMapHeight
|
||||
result = 31 * result + (lensShadingMapGrid?.contentHashCode() ?: 0)
|
||||
result = 31 * result + (appliedLensShading?.hashCode() ?: 0)
|
||||
result = 31 * result + (denoiseHistory?.hashCode() ?: 0)
|
||||
result = 31 * result + postRawSensitivityBoost.hashCode()
|
||||
result = 31 * result + baselineExposure.hashCode()
|
||||
result = 31 * result + shadowScale.hashCode()
|
||||
@@ -1229,11 +1218,6 @@ data class RawMetadata(
|
||||
result = 31 * result + frameCount
|
||||
result = 31 * result + channelNoiseProfile.contentHashCode()
|
||||
result = 31 * result + noiseProfileLayout.hashCode()
|
||||
result = 31 * result + (mgcDenoiseCorrelation?.contentHashCode() ?: 0)
|
||||
result = 31 * result + (mgcDenoiseReadNoise?.contentHashCode() ?: 0)
|
||||
result = 31 * result + (mgcDenoiseShotNoise?.contentHashCode() ?: 0)
|
||||
result = 31 * result + (mgcSpatialStrengthMap?.hashCode() ?: 0)
|
||||
result = 31 * result + (mgcDenoiseTuningSnr?.hashCode() ?: 0)
|
||||
result = 31 * result + (mgcSharpenTuningSnr?.hashCode() ?: 0)
|
||||
result = 31 * result + (mgcSharpenAttenuationScale?.hashCode() ?: 0)
|
||||
result = 31 * result + rawMaxQualityTuningEnabled.hashCode()
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.hinnka.mycamera.raw.denoise
|
||||
|
||||
import android.content.Context
|
||||
import android.opengl.GLES30
|
||||
import com.hinnka.mycamera.processor.RawStackRuntimeDebug
|
||||
import com.hinnka.mycamera.raw.RawMetadata
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import com.hinnka.mycamera.utils.SystemPropertiesUtil
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.nio.channels.Channels
|
||||
|
||||
/**
|
||||
* Debug-only export of the denoiser input (docs/photon-multiscale-denoise.md §12.4).
|
||||
*
|
||||
* Writes the camera-RGB RGBA16F pixels exactly as the denoiser receives them, plus the
|
||||
* metadata the noise model needs (profile, white balance, the LSC gains contained in the
|
||||
* pixels, pipeline, frame count), for tools/photon_denoise. Selected through
|
||||
* debug.photon.denoise.dump; files go to the app's external files dir so `adb pull` works
|
||||
* without run-as.
|
||||
*/
|
||||
internal object PhotonDenoiseDump {
|
||||
private const val TAG = "PhotonDenoiseDump"
|
||||
private const val DIRECTORY = "photon_denoise_dump"
|
||||
|
||||
val enabled: Boolean
|
||||
get() = RawStackRuntimeDebug.enabled &&
|
||||
SystemPropertiesUtil.get("debug.photon.denoise.dump")?.toBooleanStrictOrNull() == true
|
||||
|
||||
/**
|
||||
* Dumps [inputTexture] (RGBA16F camera RGB as the denoiser receives it) with its metadata
|
||||
* and the noise model [params] (`<stem>.params.json`, read by tools/photon_denoise), and,
|
||||
* when [parityEnabled], the pass-by-pass parity dump. [lensShadingSource] names where the
|
||||
* LSC gains in the pixels come from ("merge", "demosaic"). Must run on the GL thread that
|
||||
* owns [inputTexture].
|
||||
*/
|
||||
fun write(
|
||||
context: Context,
|
||||
label: String,
|
||||
inputTexture: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
metadata: RawMetadata,
|
||||
params: PhotonDenoiseParams,
|
||||
lensShadingSource: String?,
|
||||
) {
|
||||
val directory = directory(context)
|
||||
val stem = "${System.currentTimeMillis()}_${label}_${params.originX}_${params.originY}"
|
||||
runCatching {
|
||||
val pixels = readTexture(inputTexture, width, height, float32 = false)
|
||||
FileOutputStream(File(directory, "$stem.rgba16f")).use { Channels.newChannel(it).write(pixels) }
|
||||
File(directory, "$stem.json").writeText(describe(width, height, metadata, params, lensShadingSource).toString(2))
|
||||
File(directory, "$stem.params.json").writeText(params.toJson().toString(2))
|
||||
PLog.i(TAG, "Denoise input dumped: ${directory.absolutePath}/$stem.{rgba16f,json,params.json} ${width}x$height")
|
||||
}.onFailure { error -> PLog.e(TAG, "Denoise input dump failed: $stem", error) }
|
||||
if (parityEnabled) runPhotonParity(directory, stem, inputTexture, width, height, params)
|
||||
}
|
||||
|
||||
/**
|
||||
* Selected through debug.photon.denoise.parity: additionally runs the Photon denoiser and
|
||||
* dumps every pass (≈350 MB per 6 MP capture), for implementation-step-3 parity.
|
||||
*/
|
||||
val parityEnabled: Boolean
|
||||
get() = enabled &&
|
||||
SystemPropertiesUtil.get("debug.photon.denoise.parity")?.toBooleanStrictOrNull() == true
|
||||
|
||||
private fun directory(context: Context) = File(context.getExternalFilesDir(null), DIRECTORY).apply { mkdirs() }
|
||||
|
||||
private fun readTexture(texture: Int, width: Int, height: Int, float32: Boolean): ByteBuffer {
|
||||
val buffer = ByteBuffer.allocateDirect(width * height * 4 * if (float32) 4 else 2).order(ByteOrder.nativeOrder())
|
||||
val framebuffer = IntArray(1)
|
||||
GLES30.glGenFramebuffers(1, framebuffer, 0)
|
||||
try {
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer[0])
|
||||
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
|
||||
GLES30.GL_TEXTURE_2D, texture, 0)
|
||||
check(GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE) {
|
||||
"Texture $texture is not readable"
|
||||
}
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 4)
|
||||
GLES30.glReadPixels(0, 0, width, height, GLES30.GL_RGBA,
|
||||
if (float32) GLES30.GL_FLOAT else GLES30.GL_HALF_FLOAT, buffer)
|
||||
} finally {
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
GLES30.glDeleteFramebuffers(1, framebuffer, 0)
|
||||
}
|
||||
return buffer
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the Photon denoiser on the same input texture and dumps every pass output next to the
|
||||
* input dump [stem] (implementation step 3 parity, tools/photon_denoise/compare_passes.py).
|
||||
*/
|
||||
private fun runPhotonParity(directory: File, stem: String, inputTexture: Int, width: Int, height: Int,
|
||||
params: PhotonDenoiseParams) {
|
||||
val passes = JSONArray()
|
||||
val denoiser = PhotonMultiScaleDenoiser()
|
||||
val startNs = System.nanoTime()
|
||||
runCatching {
|
||||
val output = denoiser.denoise(inputTexture, width, height, params) { name, texture, w, h, float32 ->
|
||||
val buffer = readTexture(texture, w, h, float32)
|
||||
val suffix = if (float32) "f32" else "f16"
|
||||
FileOutputStream(File(directory, "$stem.$name.$suffix")).use { Channels.newChannel(it).write(buffer) }
|
||||
passes.put(JSONObject().apply {
|
||||
put("name", name)
|
||||
put("width", w)
|
||||
put("height", h)
|
||||
put("format", suffix)
|
||||
})
|
||||
} ?: error("Photon denoiser programs are unavailable")
|
||||
GLES30.glDeleteTextures(1, intArrayOf(output), 0)
|
||||
File(directory, "$stem.photon.json").writeText(JSONObject().apply {
|
||||
put("params", params.toJson())
|
||||
put("passes", passes)
|
||||
}.toString(2))
|
||||
PLog.i(TAG, "Photon parity dumped: $stem passes=${passes.length()} " +
|
||||
"ms=${(System.nanoTime() - startNs) / 1_000_000L}")
|
||||
}.onFailure { error -> PLog.e(TAG, "Photon parity run failed: $stem", error) }
|
||||
denoiser.release()
|
||||
}
|
||||
|
||||
private fun describe(
|
||||
width: Int,
|
||||
height: Int,
|
||||
metadata: RawMetadata,
|
||||
params: PhotonDenoiseParams,
|
||||
lensShadingSource: String?,
|
||||
): JSONObject = JSONObject().apply {
|
||||
put("format", "rgba16f_camera_rgb_un_white_balanced")
|
||||
put("pipeline", params.pipeline.name)
|
||||
put("width", width)
|
||||
put("height", height)
|
||||
put("originX", params.originX)
|
||||
put("originY", params.originY)
|
||||
put("fullWidth", params.fullWidth)
|
||||
put("fullHeight", params.fullHeight)
|
||||
put("cfaPattern", metadata.cfaPattern)
|
||||
put("frameCount", metadata.frameCount)
|
||||
put("iso", metadata.iso)
|
||||
put("whiteBalanceGains", JSONArray(metadata.whiteBalanceGains.toList()))
|
||||
put("noiseProfileLayout", metadata.noiseProfileLayout.name)
|
||||
put("channelNoiseProfile", JSONArray(metadata.channelNoiseProfile.toList()))
|
||||
put("profileRgbRead", JSONArray(params.read.toList()))
|
||||
put("profileRgbShot", JSONArray(params.shot.toList()))
|
||||
val lensShading = params.lensShading
|
||||
if (lensShading != null) {
|
||||
put("lensShading", JSONObject().apply {
|
||||
put("source", lensShadingSource ?: "unknown")
|
||||
put("width", lensShading.width)
|
||||
put("height", lensShading.height)
|
||||
put("layout", "R,Ge,Go,B interleaved")
|
||||
lensShading.dngGrid?.let { put("dngGrid", JSONArray(it.toList())) }
|
||||
put("gains", JSONArray(lensShading.gains.take(lensShading.width * lensShading.height * 4)))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
package com.hinnka.mycamera.raw.denoise
|
||||
|
||||
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
|
||||
|
||||
/**
|
||||
* GLES 3.1 compute passes of the Photon denoiser (docs/photon-multiscale-denoise.md §3–§8, §10).
|
||||
*
|
||||
* Each program mirrors one function of tools/photon_denoise/photon_denoise.py: Analyze = down,
|
||||
* Band = band, Pilot = pilot, Final = final + output. Arithmetic is highp; stores round to the
|
||||
* image format (RGBA16F, noise RGBA32F). Pyramid borders reflect without edge repetition.
|
||||
*/
|
||||
internal object PhotonDenoiseShaders {
|
||||
private const val LOCAL = GlesComputeWorkGroup.IMAGE_TILE_SIZE
|
||||
|
||||
private val COMMON = """
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp sampler2D;
|
||||
|
||||
layout(local_size_x = $LOCAL, local_size_y = $LOCAL) in;
|
||||
|
||||
const float LUMA_TAPS[7] = float[7](
|
||||
-1.0 / 32.0, 0.0, 9.0 / 32.0, 16.0 / 32.0, 9.0 / 32.0, 0.0, -1.0 / 32.0);
|
||||
const float CHROMA_TAPS[5] = float[5](
|
||||
1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0);
|
||||
const float CLIP_LEVEL = 0.98;
|
||||
const float PI = 3.14159265358979;
|
||||
|
||||
int mirrorIndex(int i, int n) {
|
||||
if (n == 1) return 0;
|
||||
int period = 2 * n - 2;
|
||||
i = abs(i) % period;
|
||||
return i >= n ? period - i : i;
|
||||
}
|
||||
|
||||
ivec2 mirror2(ivec2 p, ivec2 size) {
|
||||
return ivec2(mirrorIndex(p.x, size.x), mirrorIndex(p.y, size.y));
|
||||
}
|
||||
|
||||
// Working YCbCr: Y = (R + 2G + B) / 4, Cb = B - G, Cr = R - G, and its exact inverse.
|
||||
vec3 yccFromRgb(vec3 x) {
|
||||
return vec3(0.25 * x.r + 0.5 * x.g + 0.25 * x.b, x.b - x.g, x.r - x.g);
|
||||
}
|
||||
|
||||
vec3 rgbFromYcc(vec3 c) {
|
||||
return vec3(c.x - 0.25 * c.y + 0.75 * c.z,
|
||||
c.x - 0.25 * c.y - 0.25 * c.z,
|
||||
c.x + 0.75 * c.y - 0.25 * c.z);
|
||||
}
|
||||
"""
|
||||
|
||||
/** §3: gains contained in the input, manual bilinear (clamp to edge) of the R, Ge, Go, B map. */
|
||||
private val LENS_SHADING = """
|
||||
uniform int uLscMode; // 0 none, 1 Camera2 whole-image UV, 2 DNG GainMap grid
|
||||
uniform sampler2D uLscMap;
|
||||
uniform ivec2 uLscSize;
|
||||
uniform float uLscGrid[8];
|
||||
uniform ivec2 uOrigin;
|
||||
uniform ivec2 uFullSize;
|
||||
|
||||
vec3 lscGain(vec2 globalCentre) {
|
||||
if (uLscMode == 0) return vec3(1.0);
|
||||
vec2 mapSize = vec2(uLscSize);
|
||||
vec2 uv;
|
||||
if (uLscMode == 1) {
|
||||
uv = globalCentre / vec2(uFullSize);
|
||||
} else {
|
||||
vec2 boundsOrigin = vec2(uLscGrid[4], uLscGrid[5]);
|
||||
vec2 boundsSize = max(vec2(uLscGrid[6] - uLscGrid[4], uLscGrid[7] - uLscGrid[5]), vec2(1.0));
|
||||
vec2 norm = (globalCentre - boundsOrigin) / boundsSize;
|
||||
uv = ((norm - vec2(uLscGrid[0], uLscGrid[1])) / vec2(uLscGrid[2], uLscGrid[3]) + 0.5) / mapSize;
|
||||
}
|
||||
vec2 t = clamp(uv * mapSize - 0.5, vec2(0.0), mapSize - 1.0);
|
||||
ivec2 i0 = ivec2(floor(t));
|
||||
ivec2 i1 = min(i0 + 1, uLscSize - 1);
|
||||
vec2 f = t - vec2(i0);
|
||||
vec4 top = mix(texelFetch(uLscMap, i0, 0), texelFetch(uLscMap, ivec2(i1.x, i0.y), 0), f.x);
|
||||
vec4 bottom = mix(texelFetch(uLscMap, ivec2(i0.x, i1.y), 0), texelFetch(uLscMap, i1, 0), f.x);
|
||||
vec4 g = mix(top, bottom, f.y);
|
||||
return vec3(g.r, 0.5 * (g.g + g.b), g.a);
|
||||
}
|
||||
|
||||
// Level-l pixel centre in the full frame: origin + (p + 0.5) * 2^l.
|
||||
vec2 levelCentre(ivec2 p, int level) {
|
||||
return vec2(uOrigin) + (vec2(p) + 0.5) * float(1 << level);
|
||||
}
|
||||
"""
|
||||
|
||||
private val WORKING = """
|
||||
uniform sampler2D uInput; // camera RGB, RGBA16F
|
||||
uniform float uScale;
|
||||
uniform vec3 uWb;
|
||||
|
||||
vec3 working0(ivec2 p) {
|
||||
vec3 rgb = texelFetch(uInput, p, 0).rgb;
|
||||
return uScale * yccFromRgb(uWb * (rgb / lscGain(levelCentre(p, 0))));
|
||||
}
|
||||
"""
|
||||
|
||||
/** Analyze: G_{l+1} = ↓2(h * G_l), luma taps on Y and chroma taps on Cb/Cr. */
|
||||
val ANALYZE = """
|
||||
#version 310 es
|
||||
$COMMON
|
||||
$LENS_SHADING
|
||||
$WORKING
|
||||
uniform sampler2D uFine;
|
||||
uniform int uFineIsInput; // 1: level 0 computed from uInput
|
||||
uniform ivec2 uFineSize;
|
||||
uniform ivec2 uCoarseSize;
|
||||
layout(rgba16f, binding = 0) writeonly uniform highp image2D uCoarse;
|
||||
|
||||
vec3 fineAt(ivec2 p) {
|
||||
return uFineIsInput == 1 ? working0(p) : texelFetch(uFine, p, 0).rgb;
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 q = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(q, uCoarseSize))) return;
|
||||
float y = 0.0;
|
||||
vec2 c = vec2(0.0);
|
||||
for (int j = -3; j <= 3; ++j) {
|
||||
for (int i = -3; i <= 3; ++i) {
|
||||
vec3 v = fineAt(mirror2(2 * q + ivec2(i, j), uFineSize));
|
||||
y += LUMA_TAPS[i + 3] * LUMA_TAPS[j + 3] * v.x;
|
||||
if (abs(i) <= 2 && abs(j) <= 2) c += CHROMA_TAPS[i + 2] * CHROMA_TAPS[j + 2] * v.yz;
|
||||
}
|
||||
}
|
||||
imageStore(uCoarse, q, vec4(y, c, 1.0));
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
/**
|
||||
* Fused per-level synthesis: Band → Pilot → Final in one dispatch (§10.1).
|
||||
*
|
||||
* A work group owns an 8×8 output tile. Band values (L, base, noise) are computed into shared
|
||||
* memory for the tile plus a 4-pixel border, pilot values for the tile plus a 2-pixel border.
|
||||
* Shared memory is addressed by image coordinate and every neighbourhood is mirrored first,
|
||||
* exactly as in the unfused reference, so border pixels see the same values. L, base and pilot
|
||||
* are stored as packed float16 bits, rounding them exactly as their textures were rounded in
|
||||
* the unfused passes.
|
||||
*
|
||||
* [debugOutputs] compiles the parity variant: instead of the result it writes band, base,
|
||||
* noise and pilot of the tile core (tools/photon_denoise/compare_passes.py); four images, the
|
||||
* GLES 3.1 minimum. The production variant writes only the result.
|
||||
*/
|
||||
private const val DEBUG_IMAGES = """
|
||||
layout(rgba16f, binding = 0) writeonly uniform highp image2D uBandOut;
|
||||
layout(rgba16f, binding = 1) writeonly uniform highp image2D uBaseOut;
|
||||
layout(rgba32f, binding = 2) writeonly uniform highp image2D uNoiseOut;
|
||||
layout(rgba16f, binding = 3) writeonly uniform highp image2D uPilotOut;
|
||||
"""
|
||||
|
||||
private const val RESULT_IMAGE = """
|
||||
layout(rgba16f, binding = 0) writeonly uniform highp image2D uResult;
|
||||
"""
|
||||
|
||||
private const val DEBUG_STORE = """
|
||||
imageStore(uBandOut, p, vec4(lapAt(p), 0.0));
|
||||
imageStore(uBaseOut, p, vec4(baseAt(p), 0.0));
|
||||
imageStore(uNoiseOut, p, noiseAt(p));
|
||||
if (uLumaEnabled == 1) imageStore(uPilotOut, p, pilotAt(p));
|
||||
"""
|
||||
|
||||
private const val RESULT_STORE = """
|
||||
vec3 result = computeFinal(p);
|
||||
if (uWriteOutput == 1) {
|
||||
vec3 rgb = rgbFromYcc(result) / uScale / uWb * lscGain(levelCentre(p, 0));
|
||||
imageStore(uResult, p, vec4(rgb, 1.0));
|
||||
} else {
|
||||
imageStore(uResult, p, vec4(result, 1.0));
|
||||
}
|
||||
"""
|
||||
|
||||
fun synthesize(debugOutputs: Boolean): String = """
|
||||
#version 310 es
|
||||
$COMMON
|
||||
$LENS_SHADING
|
||||
$WORKING
|
||||
uniform sampler2D uFine;
|
||||
uniform int uFineIsInput;
|
||||
uniform sampler2D uNoisyCoarse;
|
||||
uniform sampler2D uDenoisedCoarse;
|
||||
uniform ivec2 uSize;
|
||||
uniform ivec2 uCoarseSize;
|
||||
uniform int uLevel;
|
||||
uniform vec3 uRead;
|
||||
uniform vec3 uShot;
|
||||
uniform float uMergeRead;
|
||||
uniform float uMergeShot;
|
||||
uniform vec3 uResidual;
|
||||
uniform float uKappaLuma[4];
|
||||
uniform float uKappaChroma[4];
|
||||
uniform float uOutlier;
|
||||
uniform float uAlpha;
|
||||
uniform int uLumaEnabled;
|
||||
uniform float uGrain;
|
||||
uniform int uChromaEnabled;
|
||||
uniform float uChromaStrength; // min(s, 1)
|
||||
uniform vec2 uGateLuma;
|
||||
uniform vec2 uGateChroma;
|
||||
uniform int uBilateral;
|
||||
uniform float uBilateralLuma;
|
||||
uniform float uBilateralChroma;
|
||||
uniform int uWriteOutput; // level 0: camera RGB with gains restored
|
||||
${if (debugOutputs) DEBUG_IMAGES else RESULT_IMAGE}
|
||||
|
||||
const int TILE = $LOCAL;
|
||||
const int BAND_BORDER = 4;
|
||||
const int PILOT_BORDER = 2;
|
||||
const int BAND_SIDE = TILE + 2 * BAND_BORDER;
|
||||
const int PILOT_SIDE = TILE + 2 * PILOT_BORDER;
|
||||
const float BASE_RADIUS = 1.25;
|
||||
|
||||
// L and base (six halves) and the pilot (four halves) are held as packed float16 bits.
|
||||
// Integer storage makes the float16 rounding unconditional: a compiler may legally fold
|
||||
// unpackHalf2x16(packHalf2x16(x)) back to x, which left unrounded values in a float array.
|
||||
shared uvec3 sLapBase[BAND_SIDE * BAND_SIDE];
|
||||
shared vec4 sNoise[BAND_SIDE * BAND_SIDE];
|
||||
shared uvec2 sPilot[PILOT_SIDE * PILOT_SIDE];
|
||||
|
||||
ivec2 tileOrigin() { return ivec2(gl_WorkGroupID.xy) * TILE; }
|
||||
int bandIndex(ivec2 c) { ivec2 r = c - (tileOrigin() - BAND_BORDER); return r.y * BAND_SIDE + r.x; }
|
||||
int pilotIndex(ivec2 c) { ivec2 r = c - (tileOrigin() - PILOT_BORDER); return r.y * PILOT_SIDE + r.x; }
|
||||
|
||||
vec3 upAt(sampler2D coarse, ivec2 p) {
|
||||
float y = 0.0;
|
||||
vec2 c = vec2(0.0);
|
||||
for (int j = -3; j <= 3; ++j) {
|
||||
if (((p.y - j) & 1) != 0) continue;
|
||||
int cy = mirrorIndex((p.y - j) / 2, uCoarseSize.y);
|
||||
for (int i = -3; i <= 3; ++i) {
|
||||
if (((p.x - i) & 1) != 0) continue;
|
||||
int cx = mirrorIndex((p.x - i) / 2, uCoarseSize.x);
|
||||
vec3 v = texelFetch(coarse, ivec2(cx, cy), 0).rgb;
|
||||
y += 4.0 * LUMA_TAPS[i + 3] * LUMA_TAPS[j + 3] * v.x;
|
||||
if (abs(i) <= 2 && abs(j) <= 2) c += 4.0 * CHROMA_TAPS[i + 2] * CHROMA_TAPS[j + 2] * v.yz;
|
||||
}
|
||||
}
|
||||
return vec3(y, c);
|
||||
}
|
||||
|
||||
// Band at image pixel p: L = G_l − ↑G_{l+1}, base = ↑G̃_{l+1}, noise = §2.1.
|
||||
void computeBand(ivec2 p) {
|
||||
vec3 fine = uFineIsInput == 1 ? working0(p) : texelFetch(uFine, p, 0).rgb;
|
||||
vec3 base = upAt(uDenoisedCoarse, p);
|
||||
vec3 lap = fine - upAt(uNoisyCoarse, p);
|
||||
vec3 mu = max(rgbFromYcc(base) / uScale / uWb, vec3(0.0));
|
||||
vec3 v = uMergeRead * uRead + uMergeShot * uShot * mu;
|
||||
vec3 aY = uScale * vec3(0.25, 0.5, 0.25) * uWb;
|
||||
vec3 aCb = uScale * vec3(0.0, -1.0, 1.0) * uWb;
|
||||
vec3 aCr = uScale * vec3(1.0, -1.0, 0.0) * uWb;
|
||||
int phase = (p.y & 1) * 2 + (p.x & 1);
|
||||
float kl = uKappaLuma[phase];
|
||||
float kc = uKappaChroma[phase];
|
||||
vec3 t = sqrt(uResidual);
|
||||
vec4 noise = vec4(
|
||||
kl * dot(aY * aY, v) * t.x * t.x,
|
||||
kc * dot(aCb * aCb, v) * t.y * t.y,
|
||||
kc * dot(aCr * aCr, v) * t.z * t.z,
|
||||
kc * dot(aCb * aCr, v) * t.y * t.z);
|
||||
vec3 camera = mu * lscGain(levelCentre(p, uLevel));
|
||||
if (any(greaterThanEqual(camera, vec3(CLIP_LEVEL)))) noise = vec4(0.0);
|
||||
int index = bandIndex(p);
|
||||
sLapBase[index] = uvec3(packHalf2x16(lap.xy), packHalf2x16(vec2(lap.z, base.x)), packHalf2x16(base.yz));
|
||||
sNoise[index] = noise;
|
||||
}
|
||||
|
||||
vec3 lapAt(ivec2 p) {
|
||||
uvec3 u = sLapBase[bandIndex(mirror2(p, uSize))];
|
||||
return vec3(unpackHalf2x16(u.x), unpackHalf2x16(u.y).x);
|
||||
}
|
||||
vec3 baseAt(ivec2 p) {
|
||||
uvec3 u = sLapBase[bandIndex(mirror2(p, uSize))];
|
||||
return vec3(unpackHalf2x16(u.y).y, unpackHalf2x16(u.z));
|
||||
}
|
||||
vec4 noiseAt(ivec2 p) { return sNoise[bandIndex(mirror2(p, uSize))]; }
|
||||
vec4 pilotAt(ivec2 p) {
|
||||
uvec2 u = sPilot[pilotIndex(mirror2(p, uSize))];
|
||||
return vec4(unpackHalf2x16(u.x), unpackHalf2x16(u.y));
|
||||
}
|
||||
|
||||
// §6.1 steps 1–2: anisotropic spatial weight × Huber weight of window offset d.
|
||||
float windowWeight(ivec2 d, float lapP, float lapQ, float sigma, float anisotropy, float c, float s) {
|
||||
float rPar = BASE_RADIUS * (1.0 + anisotropy);
|
||||
float rPerp = BASE_RADIUS * (1.0 - 0.6 * anisotropy);
|
||||
float dPar = float(d.x) * c + float(d.y) * s;
|
||||
float dPerp = -float(d.x) * s + float(d.y) * c;
|
||||
float spatial = exp(-0.5 * (dPar * dPar / (rPar * rPar) + dPerp * dPerp / (rPerp * rPerp)));
|
||||
// Equal to min(1, dσ/|Δ|) except that the centre (Δ = 0) keeps weight 1 when σ = 0, so
|
||||
// the window never sums to zero in clipped regions.
|
||||
float distance = abs(lapQ - lapP);
|
||||
float limit = uOutlier * sigma;
|
||||
float huber = distance <= limit ? 1.0 : limit / distance;
|
||||
return spatial * huber;
|
||||
}
|
||||
|
||||
// Pilot at image pixel p (§6.1 steps 1–3): (ŝ₁, anisotropy, cos θ, sin θ).
|
||||
vec4 computePilot(ivec2 p) {
|
||||
float jxx = 0.0;
|
||||
float jxy = 0.0;
|
||||
float jyy = 0.0;
|
||||
for (int dy = -1; dy <= 1; ++dy) {
|
||||
for (int dx = -1; dx <= 1; ++dx) {
|
||||
ivec2 q = mirror2(p + ivec2(dx, dy), uSize);
|
||||
float gx = 0.5 * (baseAt(q + ivec2(1, 0)).x - baseAt(q - ivec2(1, 0)).x);
|
||||
float gy = 0.5 * (baseAt(q + ivec2(0, 1)).x - baseAt(q - ivec2(0, 1)).x);
|
||||
jxx += gx * gx;
|
||||
jxy += gx * gy;
|
||||
jyy += gy * gy;
|
||||
}
|
||||
}
|
||||
jxx /= 9.0;
|
||||
jxy /= 9.0;
|
||||
jyy /= 9.0;
|
||||
float lapP = lapAt(p).x;
|
||||
float noiseP = noiseAt(p).x;
|
||||
float root = sqrt((jxx - jyy) * (jxx - jyy) + 4.0 * jxy * jxy);
|
||||
float anisotropy = clamp(root / (jxx + jyy + noiseP + 1e-12), 0.0, 1.0);
|
||||
// atan(0, 0) is undefined in GLSL: a degenerate tensor has no orientation, and with
|
||||
// zero anisotropy the window is circular, so the orientation is fixed explicitly.
|
||||
float theta = root > 0.0 ? 0.5 * atan(2.0 * jxy, jxx - jyy) + 0.5 * PI : 0.5 * PI;
|
||||
float c = cos(theta);
|
||||
float s = sin(theta);
|
||||
float sigma = sqrt(noiseP);
|
||||
float num = 0.0;
|
||||
float den = 0.0;
|
||||
for (int dy = -2; dy <= 2; ++dy) {
|
||||
for (int dx = -2; dx <= 2; ++dx) {
|
||||
ivec2 d = ivec2(dx, dy);
|
||||
float lapQ = lapAt(p + d).x;
|
||||
float w = windowWeight(d, lapP, lapQ, sigma, anisotropy, c, s);
|
||||
num += w * (lapQ * lapQ - noiseAt(p + d).x);
|
||||
den += w;
|
||||
}
|
||||
}
|
||||
float energy = max(num / den, 0.0);
|
||||
float s1 = noiseP > 0.0 ? lapP * energy / (energy + uAlpha * noiseP + 1e-30) : lapP;
|
||||
return vec4(s1, anisotropy, c, s);
|
||||
}
|
||||
|
||||
float mahalanobis(vec2 d, vec4 noise) {
|
||||
float det = noise.y * noise.z - noise.w * noise.w;
|
||||
if (det <= 0.0) return -1.0;
|
||||
return (noise.z * d.x * d.x - 2.0 * noise.w * d.x * d.y + noise.y * d.y * d.y) / max(det, 1e-30);
|
||||
}
|
||||
|
||||
// Final at image pixel p (§6.1–6.2, §7.2–7.3).
|
||||
vec3 computeFinal(ivec2 p) {
|
||||
vec3 lap = lapAt(p);
|
||||
vec3 base = baseAt(p);
|
||||
vec4 noise = noiseAt(p);
|
||||
|
||||
float lumaBand = lap.x;
|
||||
if (uLumaEnabled == 1) {
|
||||
vec4 pilotP = pilotAt(p);
|
||||
float sigma = sqrt(noise.x);
|
||||
float num = 0.0;
|
||||
float den = 0.0;
|
||||
for (int dy = -2; dy <= 2; ++dy) {
|
||||
for (int dx = -2; dx <= 2; ++dx) {
|
||||
ivec2 d = ivec2(dx, dy);
|
||||
float w = windowWeight(d, lap.x, lapAt(p + d).x, sigma, pilotP.y, pilotP.z, pilotP.w);
|
||||
float s1 = pilotAt(p + d).x;
|
||||
num += w * s1 * s1;
|
||||
den += w;
|
||||
}
|
||||
}
|
||||
float energy = num / den;
|
||||
float shrunk = noise.x > 0.0 ? lap.x * energy / (energy + uAlpha * noise.x + 1e-30) : lap.x;
|
||||
lumaBand = shrunk + uGrain * (lap.x - shrunk);
|
||||
}
|
||||
|
||||
vec2 chromaBand = lap.yz;
|
||||
vec2 baseChroma = base.yz;
|
||||
if (uChromaEnabled == 1) {
|
||||
float sumL2 = 0.0;
|
||||
float sumS2 = 0.0;
|
||||
for (int dy = -1; dy <= 1; ++dy) {
|
||||
for (int dx = -1; dx <= 1; ++dx) {
|
||||
float l = lapAt(p + ivec2(dx, dy)).x;
|
||||
sumL2 += l * l;
|
||||
sumS2 += noiseAt(p + ivec2(dx, dy)).x;
|
||||
}
|
||||
}
|
||||
float gateY = sumS2 > 0.0 ? smoothstep(uGateLuma.x, uGateLuma.y, 9.0 * sumL2 / max(sumS2, 1e-30)) : 1.0;
|
||||
float stat = mahalanobis(lap.yz, noise);
|
||||
float gateC = stat >= 0.0 ? smoothstep(uGateChroma.x, uGateChroma.y, stat) : 1.0;
|
||||
float gate = max(gateY, gateC);
|
||||
chromaBand = (uChromaStrength * gate + (1.0 - uChromaStrength)) * lap.yz;
|
||||
|
||||
if (uBilateral == 1) {
|
||||
vec2 sum = vec2(0.0);
|
||||
float weight = 0.0;
|
||||
for (int dy = -2; dy <= 2; ++dy) {
|
||||
for (int dx = -2; dx <= 2; ++dx) {
|
||||
vec3 bq = baseAt(p + ivec2(dx, dy));
|
||||
float spatial = exp(-0.5 * float(dx * dx + dy * dy) / (1.5 * 1.5));
|
||||
float dl = bq.x - base.x;
|
||||
float lumaW = noise.x > 0.0
|
||||
? exp(-dl * dl / (2.0 * uBilateralLuma * max(noise.x, 1e-30)))
|
||||
: (dl == 0.0 ? 1.0 : 0.0);
|
||||
float d2 = mahalanobis(bq.yz - base.yz, noise);
|
||||
float w = spatial * lumaW * exp(-max(d2, 0.0) / (2.0 * uBilateralChroma));
|
||||
sum += w * bq.yz;
|
||||
weight += w;
|
||||
}
|
||||
}
|
||||
baseChroma = sum / weight;
|
||||
}
|
||||
}
|
||||
return vec3(base.x + lumaBand, baseChroma + chromaBand);
|
||||
}
|
||||
|
||||
void main() {
|
||||
int lid = int(gl_LocalInvocationIndex);
|
||||
ivec2 origin = tileOrigin();
|
||||
for (int i = lid; i < BAND_SIDE * BAND_SIDE; i += TILE * TILE) {
|
||||
ivec2 c = origin - BAND_BORDER + ivec2(i % BAND_SIDE, i / BAND_SIDE);
|
||||
if (all(greaterThanEqual(c, ivec2(0))) && all(lessThan(c, uSize))) computeBand(c);
|
||||
}
|
||||
memoryBarrierShared();
|
||||
barrier();
|
||||
if (uLumaEnabled == 1) {
|
||||
for (int i = lid; i < PILOT_SIDE * PILOT_SIDE; i += TILE * TILE) {
|
||||
ivec2 c = origin - PILOT_BORDER + ivec2(i % PILOT_SIDE, i / PILOT_SIDE);
|
||||
if (all(greaterThanEqual(c, ivec2(0))) && all(lessThan(c, uSize))) {
|
||||
vec4 pilot = computePilot(c);
|
||||
sPilot[pilotIndex(c)] = uvec2(packHalf2x16(pilot.xy), packHalf2x16(pilot.zw));
|
||||
}
|
||||
}
|
||||
}
|
||||
memoryBarrierShared();
|
||||
barrier();
|
||||
|
||||
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(p, uSize))) return;
|
||||
${if (debugOutputs) DEBUG_STORE else RESULT_STORE}
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.hinnka.mycamera.raw.denoise
|
||||
|
||||
import com.hinnka.mycamera.raw.RawDenoisePipeline
|
||||
import kotlin.math.ln
|
||||
|
||||
/**
|
||||
* Tuning of the Photon denoiser (docs/photon-multiscale-denoise.md §5, §6.4, §7.4, §9).
|
||||
*
|
||||
* One table per pipeline; each table holds nodes ordered by the noise coordinate
|
||||
* n = √(m · v_Y(0.18)) / 0.18 (§5) and is interpolated linearly in ln n, clamped at the ends.
|
||||
* A node has the shape of tools/photon_denoise/tune.py's output. Every table currently holds the
|
||||
* single pre-tuning node [DEFAULT_NODE] (α = 1 is the MMSE estimate under the model; grain,
|
||||
* outlier and gates follow the design's stated intent); tune.py's per-node results replace them.
|
||||
*/
|
||||
internal object PhotonDenoiseTuning {
|
||||
const val LUMA_LEVELS = 5
|
||||
const val MIN_CHROMA_LEVELS = 5
|
||||
const val MAX_LEVELS = 7
|
||||
|
||||
class Node(
|
||||
/** Noise coordinate n of §5. */
|
||||
val n: Float,
|
||||
/** Luma Wiener over-subtraction α_l per level. */
|
||||
val alpha: FloatArray,
|
||||
/** Luma residual noise ratio t_l per level (grain kept to avoid a plastic look). */
|
||||
val grain: FloatArray,
|
||||
/** Huber outlier distance d_l in units of σ. */
|
||||
val outlier: FloatArray,
|
||||
/** Luma significance gate of the chroma detail (χ²₉ quantiles). */
|
||||
val gateLuma: FloatArray,
|
||||
/** Chroma Mahalanobis gate (χ²₂ quantiles). */
|
||||
val gateChroma: FloatArray,
|
||||
/** Coarsest chroma levels receiving the luma-guided joint bilateral (§7.3). */
|
||||
val bilateralLevels: Int,
|
||||
val bilateralLuma: Float,
|
||||
val bilateralChroma: Float,
|
||||
) {
|
||||
init {
|
||||
require(alpha.size == MAX_LEVELS && grain.size == MAX_LEVELS && outlier.size == MAX_LEVELS)
|
||||
require(gateLuma.size == 2 && gateChroma.size == 2)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* §9 nominal Bitmap noise profile (r_bm, s_bm), applied to all three channels of linear
|
||||
* sRGB and scaled by s². Pre-tuning value: a 1/255 standard deviation at mid grey, split
|
||||
* evenly between read and shot terms; the BITMAP table's PSNR optimisation replaces it.
|
||||
*/
|
||||
const val BITMAP_READ = 0.5f / (255f * 255f)
|
||||
const val BITMAP_SHOT = 0.5f / (255f * 255f * 0.18f)
|
||||
|
||||
private val DEFAULT_NODE = Node(
|
||||
n = 1f,
|
||||
alpha = floatArrayOf(1f, 1f, 1f, 1.2f, 1.2f, 1.2f, 1.2f),
|
||||
grain = floatArrayOf(0.30f, 0.20f, 0.15f, 0.10f, 0.10f, 0.10f, 0.10f),
|
||||
outlier = floatArrayOf(2.5f, 2.5f, 2.5f, 2.5f, 2.5f, 2.5f, 2.5f),
|
||||
gateLuma = floatArrayOf(16.919f, 27.877f),
|
||||
gateChroma = floatArrayOf(5.991f, 13.816f),
|
||||
bilateralLevels = 3,
|
||||
bilateralLuma = 4f,
|
||||
bilateralChroma = 4f,
|
||||
)
|
||||
|
||||
private val TABLES: Map<RawDenoisePipeline, List<Node>> =
|
||||
RawDenoisePipeline.entries.associateWith { listOf(DEFAULT_NODE) }
|
||||
|
||||
/** Tuning of [pipeline] at noise coordinate [n]. */
|
||||
fun at(pipeline: RawDenoisePipeline, n: Float): Node {
|
||||
val nodes = TABLES.getValue(pipeline)
|
||||
if (nodes.size == 1 || n <= nodes.first().n) return nodes.first()
|
||||
if (n >= nodes.last().n) return nodes.last()
|
||||
val upper = nodes.indexOfFirst { it.n >= n }
|
||||
val a = nodes[upper - 1]
|
||||
val b = nodes[upper]
|
||||
val f = ((ln(n) - ln(a.n)) / (ln(b.n) - ln(a.n)))
|
||||
fun mix(x: FloatArray, y: FloatArray) = FloatArray(x.size) { x[it] + f * (y[it] - x[it]) }
|
||||
return Node(
|
||||
n = n,
|
||||
alpha = mix(a.alpha, b.alpha),
|
||||
grain = mix(a.grain, b.grain),
|
||||
outlier = mix(a.outlier, b.outlier),
|
||||
gateLuma = mix(a.gateLuma, b.gateLuma),
|
||||
gateChroma = mix(a.gateChroma, b.gateChroma),
|
||||
bilateralLevels = if (f < 0.5f) a.bilateralLevels else b.bilateralLevels,
|
||||
bilateralLuma = a.bilateralLuma + f * (b.bilateralLuma - a.bilateralLuma),
|
||||
bilateralChroma = a.bilateralChroma + f * (b.bilateralChroma - a.bilateralChroma),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.hinnka.mycamera.raw.denoise
|
||||
|
||||
import com.hinnka.mycamera.raw.RawDenoiseHistory
|
||||
import com.hinnka.mycamera.raw.RawDenoisePipeline
|
||||
|
||||
/**
|
||||
* §2.2 merge variance ratios from the merge's nominal frame weights
|
||||
* (docs/photon-multiscale-denoise.md).
|
||||
*
|
||||
* Every frame is described by its camera-RGB read / shot coefficients already scaled to the
|
||||
* reference exposure; the reference frame's coefficients are the profile the denoiser reads
|
||||
* from the metadata. A merge output multiplied by [outputScale] scales read variance by its
|
||||
* square and the shot coefficient by itself.
|
||||
*/
|
||||
internal class PhotonMergeNoise(
|
||||
private val pipeline: RawDenoisePipeline,
|
||||
referenceRead: FloatArray,
|
||||
referenceShot: FloatArray,
|
||||
) {
|
||||
private val referenceRead = referenceRead.sum()
|
||||
private val referenceShot = referenceShot.sum()
|
||||
private var weightSum = 0.0
|
||||
private var readSum = 0.0
|
||||
private var shotSum = 0.0
|
||||
|
||||
fun add(weight: Float, read: FloatArray, shot: FloatArray) {
|
||||
require(weight.isFinite() && weight > 0f) { "Merge frame weight must be positive, got $weight" }
|
||||
val w = weight.toDouble()
|
||||
weightSum += w
|
||||
readSum += w * w * ratio(read.sum(), referenceRead)
|
||||
shotSum += w * w * ratio(shot.sum(), referenceShot)
|
||||
}
|
||||
|
||||
fun history(outputScale: Float = 1f): RawDenoiseHistory {
|
||||
check(weightSum > 0.0) { "No merge frame was added" }
|
||||
val norm = weightSum * weightSum
|
||||
return RawDenoiseHistory(
|
||||
pipeline = pipeline,
|
||||
mergeRead = (outputScale.toDouble() * outputScale * readSum / norm).toFloat(),
|
||||
mergeShot = (outputScale.toDouble() * shotSum / norm).toFloat(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun ratio(value: Float, reference: Float): Double =
|
||||
if (reference > 0f) value.toDouble() / reference else 1.0
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package com.hinnka.mycamera.raw.denoise
|
||||
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
|
||||
import com.hinnka.mycamera.raw.RawGlesProgram
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/**
|
||||
* GLES orchestration of the Photon denoiser (docs/photon-multiscale-denoise.md §4.3, §10).
|
||||
*
|
||||
* Analyze builds G_1..G_N (G_0 is computed from the input on the fly); synthesis runs the fused
|
||||
* Band → Pilot → Final dispatch per level from coarse to fine, and level 0 writes camera RGB with
|
||||
* the LSC gains restored. Only the Gaussian levels and two adjacent denoised levels are held
|
||||
* (§10.2). A [PassSink] receives every pass output for parity checks; it adds a parity dispatch
|
||||
* per level that emits the fused pass's band, base, noise and pilot tiles.
|
||||
*/
|
||||
internal class PhotonMultiScaleDenoiser {
|
||||
/** Receives pass outputs while their textures are alive (debug parity, §12.4). */
|
||||
fun interface PassSink {
|
||||
fun onPass(name: String, textureId: Int, width: Int, height: Int, float32: Boolean)
|
||||
}
|
||||
|
||||
private var analyzeProgram = 0
|
||||
private var synthesizeProgram = 0
|
||||
private var synthesizeDebugProgram = 0
|
||||
|
||||
fun initialize(debug: Boolean = false): Boolean {
|
||||
if (analyzeProgram == 0) analyzeProgram = RawGlesProgram.compileCompute(PhotonDenoiseShaders.ANALYZE, "PhotonDenoiseAnalyze")
|
||||
if (synthesizeProgram == 0) {
|
||||
synthesizeProgram = RawGlesProgram.compileCompute(PhotonDenoiseShaders.synthesize(false), "PhotonDenoiseSynthesize")
|
||||
}
|
||||
if (debug && synthesizeDebugProgram == 0) {
|
||||
synthesizeDebugProgram =
|
||||
RawGlesProgram.compileCompute(PhotonDenoiseShaders.synthesize(true), "PhotonDenoiseSynthesizeDebug")
|
||||
}
|
||||
return analyzeProgram != 0 && synthesizeProgram != 0 && (!debug || synthesizeDebugProgram != 0)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
intArrayOf(analyzeProgram, synthesizeProgram, synthesizeDebugProgram).forEach {
|
||||
if (it != 0) GLES31.glDeleteProgram(it)
|
||||
}
|
||||
analyzeProgram = 0
|
||||
synthesizeProgram = 0
|
||||
synthesizeDebugProgram = 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Denoises [inputTexture] (RGBA16F camera RGB, [width] × [height]) and returns a new RGBA16F
|
||||
* texture owned by the caller, or null when the programs are unavailable.
|
||||
*/
|
||||
fun denoise(inputTexture: Int, width: Int, height: Int, params: PhotonDenoiseParams, sink: PassSink? = null): Int? {
|
||||
if (!initialize(debug = sink != null)) return null
|
||||
val sizes = ArrayList<IntArray>(params.levels + 1)
|
||||
sizes += intArrayOf(width, height)
|
||||
repeat(params.levels) { val s = sizes.last(); sizes += intArrayOf((s[0] + 1) / 2, (s[1] + 1) / 2) }
|
||||
val owned = ArrayList<Int>()
|
||||
fun texture(size: IntArray, format: Int) = createTexture(size[0], size[1], format).also(owned::add)
|
||||
val lscTexture = params.lensShading?.let { createLscTexture(it).also(owned::add) } ?: 0
|
||||
val output = createTexture(width, height, GLES30.GL_RGBA16F)
|
||||
try {
|
||||
val gaussians = IntArray(params.levels + 1)
|
||||
for (level in 0 until params.levels) {
|
||||
val coarse = sizes[level + 1]
|
||||
gaussians[level + 1] = texture(coarse, GLES30.GL_RGBA16F)
|
||||
GLES31.glUseProgram(analyzeProgram)
|
||||
bindCommon(analyzeProgram, inputTexture, lscTexture, params)
|
||||
bindSampler(analyzeProgram, "uFine", UNIT_FINE, if (level == 0) inputTexture else gaussians[level])
|
||||
uniform1i(analyzeProgram, "uFineIsInput", if (level == 0) 1 else 0)
|
||||
uniform2i(analyzeProgram, "uFineSize", sizes[level])
|
||||
uniform2i(analyzeProgram, "uCoarseSize", coarse)
|
||||
bindImage(0, gaussians[level + 1], GLES30.GL_RGBA16F)
|
||||
dispatch(coarse)
|
||||
sink?.onPass("G${level + 1}", gaussians[level + 1], coarse[0], coarse[1], false)
|
||||
}
|
||||
|
||||
var denoisedCoarse = gaussians[params.levels]
|
||||
for (level in params.levels - 1 downTo 0) {
|
||||
val size = sizes[level]
|
||||
val lumaEnabled = level < params.lumaLevels && params.lumaStrength > 0f
|
||||
if (sink != null) {
|
||||
// Parity variant: the same fused computation, emitting its band, base, noise
|
||||
// and pilot tiles instead of the result.
|
||||
val band = texture(size, GLES30.GL_RGBA16F)
|
||||
val base = texture(size, GLES30.GL_RGBA16F)
|
||||
val noise = texture(size, GLES30.GL_RGBA32F)
|
||||
val pilot = if (lumaEnabled) texture(size, GLES30.GL_RGBA16F) else band
|
||||
GLES31.glUseProgram(synthesizeDebugProgram)
|
||||
bindSynthesize(synthesizeDebugProgram, inputTexture, lscTexture, gaussians, denoisedCoarse,
|
||||
sizes, level, lumaEnabled, params)
|
||||
bindImage(0, band, GLES30.GL_RGBA16F)
|
||||
bindImage(1, base, GLES30.GL_RGBA16F)
|
||||
bindImage(2, noise, GLES30.GL_RGBA32F)
|
||||
bindImage(3, pilot, GLES30.GL_RGBA16F)
|
||||
dispatch(size)
|
||||
sink.onPass("band$level", band, size[0], size[1], false)
|
||||
sink.onPass("base$level", base, size[0], size[1], false)
|
||||
sink.onPass("noise$level", noise, size[0], size[1], true)
|
||||
if (lumaEnabled) sink.onPass("pilot$level", pilot, size[0], size[1], false)
|
||||
listOf(band, base, noise, pilot).distinct().forEach { scratch ->
|
||||
GLES30.glDeleteTextures(1, intArrayOf(scratch), 0)
|
||||
owned.remove(scratch)
|
||||
}
|
||||
}
|
||||
|
||||
val result = if (level == 0) output else texture(size, GLES30.GL_RGBA16F)
|
||||
GLES31.glUseProgram(synthesizeProgram)
|
||||
bindSynthesize(synthesizeProgram, inputTexture, lscTexture, gaussians, denoisedCoarse,
|
||||
sizes, level, lumaEnabled, params)
|
||||
bindImage(0, result, GLES30.GL_RGBA16F)
|
||||
dispatch(size)
|
||||
sink?.onPass(if (level == 0) "output" else "denoised$level", result, size[0], size[1], false)
|
||||
|
||||
if (denoisedCoarse != gaussians[params.levels]) {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(denoisedCoarse), 0)
|
||||
owned.remove(denoisedCoarse)
|
||||
}
|
||||
denoisedCoarse = result
|
||||
}
|
||||
RawGlesProgram.logErrors("PhotonMultiScaleDenoiser")
|
||||
return output
|
||||
} catch (error: Throwable) {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(output), 0)
|
||||
throw error
|
||||
} finally {
|
||||
if (owned.isNotEmpty()) GLES30.glDeleteTextures(owned.size, owned.toIntArray(), 0)
|
||||
GLES31.glUseProgram(0)
|
||||
}
|
||||
}
|
||||
|
||||
private fun bindCommon(program: Int, inputTexture: Int, lscTexture: Int, params: PhotonDenoiseParams) {
|
||||
bindSampler(program, "uInput", UNIT_INPUT, inputTexture)
|
||||
uniform1f(program, "uScale", params.scale)
|
||||
uniform3f(program, "uWb", params.whiteBalance)
|
||||
val lsc = params.lensShading
|
||||
uniform1i(program, "uLscMode", when {
|
||||
lsc == null -> 0
|
||||
lsc.dngGrid == null -> 1
|
||||
else -> 2
|
||||
})
|
||||
bindSampler(program, "uLscMap", UNIT_LSC, if (lscTexture != 0) lscTexture else inputTexture)
|
||||
GLES31.glUniform2i(location(program, "uLscSize"), lsc?.width ?: 1, lsc?.height ?: 1)
|
||||
GLES31.glUniform1fv(location(program, "uLscGrid"), 8, lsc?.dngGrid ?: FloatArray(8), 0)
|
||||
GLES31.glUniform2i(location(program, "uOrigin"), params.originX, params.originY)
|
||||
GLES31.glUniform2i(location(program, "uFullSize"), params.fullWidth, params.fullHeight)
|
||||
}
|
||||
|
||||
private fun bindSynthesize(
|
||||
program: Int,
|
||||
inputTexture: Int,
|
||||
lscTexture: Int,
|
||||
gaussians: IntArray,
|
||||
denoisedCoarse: Int,
|
||||
sizes: List<IntArray>,
|
||||
level: Int,
|
||||
lumaEnabled: Boolean,
|
||||
params: PhotonDenoiseParams,
|
||||
) {
|
||||
bindCommon(program, inputTexture, lscTexture, params)
|
||||
bindSampler(program, "uFine", UNIT_FINE, if (level == 0) inputTexture else gaussians[level])
|
||||
bindSampler(program, "uNoisyCoarse", UNIT_NOISY_COARSE, gaussians[level + 1])
|
||||
bindSampler(program, "uDenoisedCoarse", UNIT_DENOISED_COARSE, denoisedCoarse)
|
||||
uniform1i(program, "uFineIsInput", if (level == 0) 1 else 0)
|
||||
uniform2i(program, "uSize", sizes[level])
|
||||
uniform2i(program, "uCoarseSize", sizes[level + 1])
|
||||
uniform1i(program, "uLevel", level)
|
||||
uniform3f(program, "uRead", params.read)
|
||||
uniform3f(program, "uShot", params.shot)
|
||||
uniform1f(program, "uMergeRead", params.mergeRead)
|
||||
uniform1f(program, "uMergeShot", params.mergeShot)
|
||||
uniform3f(program, "uResidual", params.residual[level])
|
||||
GLES31.glUniform1fv(location(program, "uKappaLuma"), 4, params.kappaLuma[level], 0)
|
||||
GLES31.glUniform1fv(location(program, "uKappaChroma"), 4, params.kappaChroma[level], 0)
|
||||
uniform1f(program, "uOutlier", params.outlier[level])
|
||||
uniform1f(program, "uAlpha", params.lumaAlpha(level))
|
||||
uniform1i(program, "uLumaEnabled", if (lumaEnabled) 1 else 0)
|
||||
uniform1f(program, "uGrain", params.lumaGrain(level))
|
||||
val chromaEnabled = params.chromaStrength > 0f
|
||||
uniform1i(program, "uChromaEnabled", if (chromaEnabled) 1 else 0)
|
||||
uniform1f(program, "uChromaStrength", minOf(params.chromaStrength, 1f))
|
||||
val thresholdScale = params.chromaThresholdScale()
|
||||
GLES31.glUniform2f(location(program, "uGateLuma"),
|
||||
params.gateLuma[0] * thresholdScale, params.gateLuma[1] * thresholdScale)
|
||||
GLES31.glUniform2f(location(program, "uGateChroma"),
|
||||
params.gateChroma[0] * thresholdScale, params.gateChroma[1] * thresholdScale)
|
||||
uniform1i(program, "uBilateral", if (chromaEnabled && level >= params.levels - params.bilateralLevels) 1 else 0)
|
||||
uniform1f(program, "uBilateralLuma", params.bilateralLuma)
|
||||
uniform1f(program, "uBilateralChroma", params.bilateralChroma * thresholdScale)
|
||||
uniform1i(program, "uWriteOutput", if (level == 0) 1 else 0)
|
||||
}
|
||||
|
||||
private fun createTexture(width: Int, height: Int, format: Int): Int {
|
||||
val ids = IntArray(1)
|
||||
GLES30.glGenTextures(1, ids, 0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, ids[0])
|
||||
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, format, 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)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
return ids[0]
|
||||
}
|
||||
|
||||
private fun createLscTexture(lsc: PhotonLensShading): Int {
|
||||
val texture = createTexture(lsc.width, lsc.height, GLES30.GL_RGBA32F)
|
||||
val data = ByteBuffer.allocateDirect(lsc.width * lsc.height * 4 * Float.SIZE_BYTES).order(ByteOrder.nativeOrder())
|
||||
data.asFloatBuffer().put(lsc.gains, 0, lsc.width * lsc.height * 4)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
|
||||
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 4)
|
||||
GLES30.glTexSubImage2D(GLES30.GL_TEXTURE_2D, 0, 0, 0, lsc.width, lsc.height, GLES30.GL_RGBA, GLES30.GL_FLOAT, data)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
return texture
|
||||
}
|
||||
|
||||
private fun dispatch(size: IntArray) {
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount(size[0]),
|
||||
GlesComputeWorkGroup.imageGroupCount(size[1]),
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
|
||||
)
|
||||
}
|
||||
|
||||
private fun bindImage(unit: Int, texture: Int, format: Int) {
|
||||
GLES31.glBindImageTexture(unit, texture, 0, false, 0, GLES31.GL_WRITE_ONLY, format)
|
||||
}
|
||||
|
||||
private fun bindSampler(program: Int, name: String, unit: Int, texture: Int) {
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + unit)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, texture)
|
||||
GLES31.glUniform1i(location(program, name), unit)
|
||||
}
|
||||
|
||||
private fun location(program: Int, name: String) = GLES31.glGetUniformLocation(program, name)
|
||||
private fun uniform1i(program: Int, name: String, value: Int) = GLES31.glUniform1i(location(program, name), value)
|
||||
private fun uniform1f(program: Int, name: String, value: Float) = GLES31.glUniform1f(location(program, name), value)
|
||||
private fun uniform2i(program: Int, name: String, size: IntArray) =
|
||||
GLES31.glUniform2i(location(program, name), size[0], size[1])
|
||||
private fun uniform3f(program: Int, name: String, v: FloatArray) =
|
||||
GLES31.glUniform3f(location(program, name), v[0], v[1], v[2])
|
||||
|
||||
private companion object {
|
||||
const val UNIT_INPUT = 0
|
||||
const val UNIT_LSC = 1
|
||||
const val UNIT_FINE = 2
|
||||
const val UNIT_NOISY_COARSE = 3
|
||||
const val UNIT_DENOISED_COARSE = 4
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
package com.hinnka.mycamera.raw.denoise
|
||||
|
||||
import com.hinnka.mycamera.processor.RawNoiseModel
|
||||
import com.hinnka.mycamera.raw.RawAppliedLensShading
|
||||
import com.hinnka.mycamera.raw.RawDenoiseHistory
|
||||
import com.hinnka.mycamera.raw.RawDenoisePipeline
|
||||
import com.hinnka.mycamera.raw.RawMetadata
|
||||
import com.hinnka.mycamera.raw.RawNoiseProfileLayout
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* LSC gains contained in the denoiser input (docs/photon-multiscale-denoise.md §3).
|
||||
* [gains] is R, Ge, Go, B interleaved; [dngGrid] null means Camera2 whole-image UV.
|
||||
*/
|
||||
internal class PhotonLensShading(
|
||||
val gains: FloatArray,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val dngGrid: FloatArray?,
|
||||
) {
|
||||
init {
|
||||
require(width > 0 && height > 0 && gains.size >= width * height * 4)
|
||||
require(dngGrid == null || dngGrid.size >= 8)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun applied(value: RawAppliedLensShading) = PhotonLensShading(value.gains, value.width, value.height, null)
|
||||
|
||||
fun demosaic(metadata: RawMetadata): PhotonLensShading? {
|
||||
val map = metadata.lensShadingMap ?: return null
|
||||
val w = metadata.lensShadingMapWidth
|
||||
val h = metadata.lensShadingMapHeight
|
||||
if (w <= 0 || h <= 0 || map.size < w * h * 4) return null
|
||||
return PhotonLensShading(map, w, h, metadata.lensShadingMapGrid?.takeIf { it.size >= 8 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Every value the Photon denoiser passes consume; mirrored by tools/photon_denoise/photon_denoise.Params. */
|
||||
internal class PhotonDenoiseParams(
|
||||
val pipeline: RawDenoisePipeline,
|
||||
/** §5 noise coordinate the tuning was taken at. */
|
||||
val noiseCoordinate: Float,
|
||||
val scale: Float,
|
||||
val whiteBalance: FloatArray,
|
||||
val read: FloatArray,
|
||||
val shot: FloatArray,
|
||||
val mergeRead: Float,
|
||||
val mergeShot: Float,
|
||||
/** §2.4 t² per level as (Y, Cb, Cr). */
|
||||
val residual: Array<FloatArray>,
|
||||
val kappaLuma: Array<FloatArray>,
|
||||
val kappaChroma: Array<FloatArray>,
|
||||
val levels: Int,
|
||||
val lumaLevels: Int,
|
||||
val alpha: FloatArray,
|
||||
val grain: FloatArray,
|
||||
val outlier: FloatArray,
|
||||
val gateLuma: FloatArray,
|
||||
val gateChroma: FloatArray,
|
||||
val bilateralLevels: Int,
|
||||
val bilateralLuma: Float,
|
||||
val bilateralChroma: Float,
|
||||
val lumaStrength: Float,
|
||||
val chromaStrength: Float,
|
||||
val lensShading: PhotonLensShading?,
|
||||
val originX: Int,
|
||||
val originY: Int,
|
||||
val fullWidth: Int,
|
||||
val fullHeight: Int,
|
||||
) {
|
||||
/** §8: residual ratio t_l(s). */
|
||||
fun lumaGrain(level: Int): Float {
|
||||
val t = grain[level]
|
||||
val s = lumaStrength
|
||||
return if (s <= 1f) 1f - s * (1f - t) else t * (2f - s)
|
||||
}
|
||||
|
||||
/** §8: α_l · max(s, 1)². */
|
||||
fun lumaAlpha(level: Int): Float = alpha[level] * max(lumaStrength, 1f).let { it * it }
|
||||
|
||||
/** §8: χ² thresholds scaled by max(s, 1)². */
|
||||
fun chromaThresholdScale(): Float = max(chromaStrength, 1f).let { it * it }
|
||||
|
||||
/**
|
||||
* §2.4: noise state of this pass's output. Flat-region worst case per level: luma keeps
|
||||
* t_l(s)² of its input variance where it is shrunk; chroma detail keeps (1 − min(s, 1))²
|
||||
* (gate closed). Levels this pass does not process keep their input ratio.
|
||||
*/
|
||||
fun outputHistory(): RawDenoiseHistory {
|
||||
val chromaKept = (1f - min(chromaStrength, 1f)).let { it * it }
|
||||
val residualOut = List(max(levels, residual.size)) { level ->
|
||||
val input = residual.getOrNull(level) ?: floatArrayOf(1f, 1f, 1f)
|
||||
if (level >= levels) return@List input.copyOf()
|
||||
val luma = if (level < lumaLevels && lumaStrength > 0f) lumaGrain(level).let { it * it } else 1f
|
||||
val chroma = if (chromaStrength > 0f) chromaKept else 1f
|
||||
floatArrayOf(input[0] * luma, input[1] * chroma, input[2] * chroma)
|
||||
}
|
||||
return RawDenoiseHistory(pipeline, mergeRead, mergeShot, residualOut)
|
||||
}
|
||||
|
||||
fun toJson(): JSONObject = JSONObject().apply {
|
||||
put("pipeline", pipeline.name)
|
||||
put("noiseCoordinate", noiseCoordinate.toDouble())
|
||||
put("scale", scale.toDouble())
|
||||
put("whiteBalance", JSONArray(whiteBalance.map(Float::toDouble)))
|
||||
put("read", JSONArray(read.map(Float::toDouble)))
|
||||
put("shot", JSONArray(shot.map(Float::toDouble)))
|
||||
put("mergeRead", mergeRead.toDouble())
|
||||
put("mergeShot", mergeShot.toDouble())
|
||||
put("residual", JSONArray(residual.map { row -> JSONArray(row.map(Float::toDouble)) }))
|
||||
put("kappaLuma", JSONArray(kappaLuma.map { row -> JSONArray(row.map(Float::toDouble)) }))
|
||||
put("kappaChroma", JSONArray(kappaChroma.map { row -> JSONArray(row.map(Float::toDouble)) }))
|
||||
put("levels", levels)
|
||||
put("lumaLevels", lumaLevels)
|
||||
put("alpha", JSONArray(alpha.map(Float::toDouble)))
|
||||
put("grain", JSONArray(grain.map(Float::toDouble)))
|
||||
put("outlier", JSONArray(outlier.map(Float::toDouble)))
|
||||
put("gateLuma", JSONArray(gateLuma.map(Float::toDouble)))
|
||||
put("gateChroma", JSONArray(gateChroma.map(Float::toDouble)))
|
||||
put("bilateralLevels", bilateralLevels)
|
||||
put("bilateralLuma", bilateralLuma.toDouble())
|
||||
put("bilateralChroma", bilateralChroma.toDouble())
|
||||
put("lumaStrength", lumaStrength.toDouble())
|
||||
put("chromaStrength", chromaStrength.toDouble())
|
||||
put("originX", originX)
|
||||
put("originY", originY)
|
||||
put("fullWidth", fullWidth)
|
||||
put("fullHeight", fullHeight)
|
||||
lensShading?.let { lsc ->
|
||||
put("lensShading", JSONObject().apply {
|
||||
put("width", lsc.width)
|
||||
put("height", lsc.height)
|
||||
put("gains", JSONArray(lsc.gains.take(lsc.width * lsc.height * 4).map(Float::toDouble)))
|
||||
lsc.dngGrid?.let { put("dngGrid", JSONArray(it.map(Float::toDouble))) }
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** §2: RAW profile × white-noise energy of the pyramid. */
|
||||
internal object PhotonNoiseModel {
|
||||
private const val MAX_WORKING_SIGNAL = 32768f
|
||||
private const val MAX_SCALE = 4096f
|
||||
private const val LSB_FRACTION = 0.25f
|
||||
private const val MIN_LEVEL_SIZE = 4
|
||||
|
||||
/**
|
||||
* RAW input. [history]: §2.2 merge ratios, §2.4 residual ratios and pipeline of the pixels.
|
||||
*/
|
||||
fun build(
|
||||
metadata: RawMetadata,
|
||||
width: Int,
|
||||
height: Int,
|
||||
originX: Int,
|
||||
originY: Int,
|
||||
fullWidth: Int,
|
||||
fullHeight: Int,
|
||||
history: RawDenoiseHistory,
|
||||
lumaStrength: Float,
|
||||
chromaStrength: Float,
|
||||
lensShading: PhotonLensShading?,
|
||||
): PhotonDenoiseParams? {
|
||||
val noise = profileNoise(metadata) ?: return null
|
||||
val gains = metadata.whiteBalanceGains
|
||||
val green = if (gains.size >= 4) 0.5f * (gains[1] + gains[2]) else gains.getOrElse(1) { 1f }
|
||||
val whiteBalance = floatArrayOf(
|
||||
gains.getOrElse(0) { 1f } / green,
|
||||
1f,
|
||||
(if (gains.size >= 4) gains[3] else gains.getOrElse(2) { 1f }) / green,
|
||||
)
|
||||
return build(noise.read, noise.shot, whiteBalance, width, height, originX, originY, fullWidth, fullHeight,
|
||||
history, lumaStrength, chromaStrength, lensShading)
|
||||
}
|
||||
|
||||
/**
|
||||
* §9 Bitmap input: linear sRGB with the nominal profile of the BITMAP table, no white
|
||||
* balance, no LSC, no merge.
|
||||
*/
|
||||
fun buildBitmap(width: Int, height: Int, lumaStrength: Float, chromaStrength: Float): PhotonDenoiseParams = build(
|
||||
read = FloatArray(3) { PhotonDenoiseTuning.BITMAP_READ },
|
||||
shot = FloatArray(3) { PhotonDenoiseTuning.BITMAP_SHOT },
|
||||
whiteBalance = floatArrayOf(1f, 1f, 1f),
|
||||
width = width,
|
||||
height = height,
|
||||
originX = 0,
|
||||
originY = 0,
|
||||
fullWidth = width,
|
||||
fullHeight = height,
|
||||
history = RawDenoiseHistory.singleFrame(RawDenoisePipeline.BITMAP),
|
||||
lumaStrength = lumaStrength,
|
||||
chromaStrength = chromaStrength,
|
||||
lensShading = null,
|
||||
)
|
||||
|
||||
/** Normalized camera-RGB read / shot coefficients of the RAW noise profile (§2.1 r_c, s_c). */
|
||||
class ProfileNoise(val read: FloatArray, val shot: FloatArray)
|
||||
|
||||
fun profileNoise(metadata: RawMetadata): ProfileNoise? {
|
||||
val rawNoise = when (metadata.noiseProfileLayout) {
|
||||
RawNoiseProfileLayout.CAMERA2_CFA -> RawNoiseModel.fromCamera2NoiseProfile(metadata.channelNoiseProfile)
|
||||
RawNoiseProfileLayout.DNG_RGB -> RawNoiseModel.fromDngNoiseProfile(metadata.channelNoiseProfile)
|
||||
RawNoiseProfileLayout.CANONICAL_BAYER -> {
|
||||
if (metadata.channelNoiseProfile.size < 8) return null
|
||||
RawNoiseModel.fromCanonicalBayerChannels(
|
||||
shotNoise = FloatArray(4) { metadata.channelNoiseProfile[it * 2] },
|
||||
readNoise = FloatArray(4) { metadata.channelNoiseProfile[it * 2 + 1] },
|
||||
)
|
||||
}
|
||||
RawNoiseProfileLayout.NONE -> RawNoiseModel.EMPTY
|
||||
}
|
||||
val bayerShot = rawNoise.normalizedShotNoiseForShader(metadata.cfaPattern)
|
||||
val bayerRead = rawNoise.normalizedReadNoiseForShader(metadata.cfaPattern)
|
||||
if (bayerShot.none { it > 0f } && bayerRead.none { it > 0f }) return null
|
||||
return ProfileNoise(
|
||||
read = RawNoiseModel.bayerNoiseModelToRgb(bayerRead),
|
||||
shot = RawNoiseModel.bayerNoiseModelToRgb(bayerShot),
|
||||
)
|
||||
}
|
||||
|
||||
/** Recorded history of a RAW source, else a single frame of the demosaic that produced it. */
|
||||
fun historyOf(metadata: RawMetadata): RawDenoiseHistory = metadata.denoiseHistory
|
||||
?: RawDenoiseHistory.singleFrame(
|
||||
if (RawMetadata.isQuadBayer(metadata.cfaPattern)) RawDenoisePipeline.QUAD else RawDenoisePipeline.VGN,
|
||||
)
|
||||
|
||||
/** §5: n = √(m · v_Y(0.18)) / 0.18, v_Y the luma point variance without K. */
|
||||
fun noiseCoordinate(read: FloatArray, shot: FloatArray, whiteBalance: FloatArray, history: RawDenoiseHistory): Float {
|
||||
val luma = floatArrayOf(0.25f, 0.5f, 0.25f)
|
||||
var variance = 0.0
|
||||
for (c in 0..2) {
|
||||
val a = luma[c] * whiteBalance[c]
|
||||
variance += a * a * (history.mergeRead * read[c] + history.mergeShot * shot[c] * 0.18f / whiteBalance[c])
|
||||
}
|
||||
return (sqrt(variance) / 0.18).toFloat()
|
||||
}
|
||||
|
||||
private fun build(
|
||||
read: FloatArray,
|
||||
shot: FloatArray,
|
||||
whiteBalance: FloatArray,
|
||||
width: Int,
|
||||
height: Int,
|
||||
originX: Int,
|
||||
originY: Int,
|
||||
fullWidth: Int,
|
||||
fullHeight: Int,
|
||||
history: RawDenoiseHistory,
|
||||
lumaStrength: Float,
|
||||
chromaStrength: Float,
|
||||
lensShading: PhotonLensShading?,
|
||||
): PhotonDenoiseParams {
|
||||
val mergeRead = history.mergeRead
|
||||
val mergeShot = history.mergeShot
|
||||
val scale = min(MAX_SCALE, MAX_WORKING_SIGNAL / whiteBalance.max())
|
||||
val sizeLimit = generateSequence(min(width, height)) { (it + 1) / 2 }
|
||||
.takeWhile { it >= MIN_LEVEL_SIZE }.count() - 1
|
||||
val maxLevels = min(PhotonDenoiseTuning.MAX_LEVELS, sizeLimit).coerceAtLeast(1)
|
||||
val unit = FloatArray(PhotonNoisePropagation.SPECTRUM_SIZE) { 1f }
|
||||
val chromaTable = PhotonNoisePropagation.propagate(unit, unit, PhotonNoisePropagation.CHROMA_TAPS, maxLevels)
|
||||
val lumaTable = PhotonNoisePropagation.propagate(unit, unit, PhotonNoisePropagation.LUMA_TAPS, maxLevels)
|
||||
val levels = chromaLevels(chromaTable, read, shot, mergeRead, mergeShot, whiteBalance, scale, maxLevels)
|
||||
fun rows(table: PhotonNoisePropagation.Table) = Array(levels) { l ->
|
||||
FloatArray(4) { phase -> table.kappaLaplacian[l][phase].toFloat() }
|
||||
}
|
||||
val n = noiseCoordinate(read, shot, whiteBalance, history)
|
||||
val tuning = PhotonDenoiseTuning.at(history.pipeline, n)
|
||||
return PhotonDenoiseParams(
|
||||
pipeline = history.pipeline,
|
||||
noiseCoordinate = n,
|
||||
scale = scale,
|
||||
whiteBalance = whiteBalance,
|
||||
read = read.copyOf(),
|
||||
shot = shot.copyOf(),
|
||||
mergeRead = mergeRead,
|
||||
mergeShot = mergeShot,
|
||||
residual = Array(levels) { history.residualAt(it) },
|
||||
kappaLuma = rows(lumaTable),
|
||||
kappaChroma = rows(chromaTable),
|
||||
levels = levels,
|
||||
lumaLevels = min(PhotonDenoiseTuning.LUMA_LEVELS, levels),
|
||||
alpha = tuning.alpha.copyOf(levels),
|
||||
grain = tuning.grain.copyOf(levels),
|
||||
outlier = tuning.outlier.copyOf(levels),
|
||||
gateLuma = tuning.gateLuma.copyOf(),
|
||||
gateChroma = tuning.gateChroma.copyOf(),
|
||||
bilateralLevels = tuning.bilateralLevels,
|
||||
bilateralLuma = tuning.bilateralLuma,
|
||||
bilateralChroma = tuning.bilateralChroma,
|
||||
lumaStrength = lumaStrength,
|
||||
chromaStrength = chromaStrength,
|
||||
lensShading = lensShading,
|
||||
originX = originX,
|
||||
originY = originY,
|
||||
fullWidth = fullWidth,
|
||||
fullHeight = fullHeight,
|
||||
)
|
||||
}
|
||||
|
||||
/** §4.2: deepest chroma level whose mid-grey noise still exceeds a quarter of a 16-bit LSB. */
|
||||
private fun chromaLevels(
|
||||
table: PhotonNoisePropagation.Table,
|
||||
read: FloatArray,
|
||||
shot: FloatArray,
|
||||
mergeRead: Float,
|
||||
mergeShot: Float,
|
||||
whiteBalance: FloatArray,
|
||||
scale: Float,
|
||||
maxLevels: Int,
|
||||
): Int {
|
||||
// Mid-grey Cb variance of independent source noise in the working domain.
|
||||
val mu = FloatArray(3) { 0.18f / whiteBalance[it] }
|
||||
val cb = floatArrayOf(0f, -1f, 1f)
|
||||
var variance = 0.0
|
||||
for (c in 0..2) {
|
||||
val a = scale * cb[c] * whiteBalance[c]
|
||||
variance += a * a * (mergeRead * read[c] + mergeShot * shot[c] * mu[c])
|
||||
}
|
||||
val threshold = LSB_FRACTION * scale / 65535f
|
||||
var levels = PhotonDenoiseTuning.MIN_CHROMA_LEVELS
|
||||
while (levels < maxLevels) {
|
||||
val kappa = table.kappaLaplacian[levels].average()
|
||||
if (sqrt(kappa * variance) < threshold) break
|
||||
levels++
|
||||
}
|
||||
return min(levels, maxLevels)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.hinnka.mycamera.raw.denoise
|
||||
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.cos
|
||||
|
||||
/**
|
||||
* Exact noise propagation through the decimated Laplacian pyramid
|
||||
* (docs/photon-multiscale-denoise.md §5.3).
|
||||
*
|
||||
* The spatial correlation is a separable spectrum P_x ⊗ P_y sampled on MGC's 128-bin
|
||||
* half-bin-centred grid. With separable filters every pyramid quantity factorises into
|
||||
* per-axis autocorrelation terms, so the tables are exact within the §2.2 model and do not
|
||||
* depend on the image size. tools/photon_denoise/noise_model.py is the reference
|
||||
* implementation and validate_propagation.py its synthetic-noise gate.
|
||||
*/
|
||||
internal object PhotonNoisePropagation {
|
||||
const val SPECTRUM_SIZE = 128
|
||||
const val MAX_LAG = 63
|
||||
const val PHASE_COUNT = 4
|
||||
|
||||
/** 4-point Deslauriers–Dubuc analysis filter: band-selective luma split, H(π) = 0. */
|
||||
val LUMA_TAPS = doubleArrayOf(-1.0, 0.0, 9.0, 16.0, 9.0, 0.0, -1.0).map { it / 32.0 }.toDoubleArray()
|
||||
|
||||
/** Binomial analysis filter: no negative lobes, so chroma edges cannot ring. */
|
||||
val CHROMA_TAPS = doubleArrayOf(1.0, 4.0, 6.0, 4.0, 1.0).map { it / 16.0 }.toDoubleArray()
|
||||
|
||||
/**
|
||||
* kappaGaussian[l] = Var[G_l] / σ², kappaLaplacian[l][phase] = Var[L_l] / σ² with
|
||||
* phase = (y & 1) * 2 + (x & 1). A spectrum that is not normalised to unit mean keeps
|
||||
* its amplitude inside these factors.
|
||||
*/
|
||||
class Table(
|
||||
val kappaGaussian: DoubleArray,
|
||||
val kappaLaplacian: Array<DoubleArray>,
|
||||
) {
|
||||
val levels: Int get() = kappaLaplacian.size
|
||||
}
|
||||
|
||||
fun propagate(
|
||||
spectrumX: FloatArray,
|
||||
spectrumY: FloatArray,
|
||||
taps: DoubleArray,
|
||||
levels: Int,
|
||||
): Table {
|
||||
require(levels > 0)
|
||||
require(taps.size % 2 == 1)
|
||||
var rx = autocorrelation(spectrumX)
|
||||
var ry = autocorrelation(spectrumY)
|
||||
val kappaGaussian = DoubleArray(levels + 1)
|
||||
val kappaLaplacian = Array(levels) { DoubleArray(PHASE_COUNT) }
|
||||
for (level in 0..levels) {
|
||||
kappaGaussian[level] = lag(rx, 0) * lag(ry, 0)
|
||||
if (level == levels) break
|
||||
val termsX = Array(2) { phase -> laplacianAxisTerms(rx, taps, phase) }
|
||||
val termsY = Array(2) { phase -> laplacianAxisTerms(ry, taps, phase) }
|
||||
for (py in 0..1) {
|
||||
for (px in 0..1) {
|
||||
val x = termsX[px]
|
||||
val y = termsY[py]
|
||||
kappaLaplacian[level][py * 2 + px] =
|
||||
x[0] * y[0] - 2.0 * x[1] * y[1] + x[2] * y[2]
|
||||
}
|
||||
}
|
||||
rx = decimateAutocorrelation(rx, taps)
|
||||
ry = decimateAutocorrelation(ry, taps)
|
||||
}
|
||||
return Table(kappaGaussian, kappaLaplacian)
|
||||
}
|
||||
|
||||
fun spectrumFrequency(index: Int): Double =
|
||||
(index + 0.5) * 2.0 * PI / SPECTRUM_SIZE - PI
|
||||
|
||||
/** r(d) = mean_k P(ω_k) cos(ω_k d) for d = -MAX_LAG..MAX_LAG, stored at d + MAX_LAG. */
|
||||
fun autocorrelation(spectrum: FloatArray): DoubleArray {
|
||||
require(spectrum.size == SPECTRUM_SIZE)
|
||||
require(spectrum.all { it.isFinite() && it >= 0f }) { "Spectrum must be finite and non-negative" }
|
||||
return DoubleArray(2 * MAX_LAG + 1) { index ->
|
||||
val d = (index - MAX_LAG).toDouble()
|
||||
var sum = 0.0
|
||||
for (k in 0 until SPECTRUM_SIZE) {
|
||||
sum += spectrum[k] * cos(spectrumFrequency(k) * d)
|
||||
}
|
||||
sum / SPECTRUM_SIZE
|
||||
}
|
||||
}
|
||||
|
||||
/** G_{l+1} = ↓2(h * G_l): r_{l+1}(d) = Σ_m (h ⋆ h̃)(m) r_l(2d − m). */
|
||||
private fun decimateAutocorrelation(r: DoubleArray, taps: DoubleArray): DoubleArray {
|
||||
val hh = autoConvolve(taps)
|
||||
val hhRadius = (hh.size - 1) / 2
|
||||
return DoubleArray(r.size) { index ->
|
||||
val d = index - MAX_LAG
|
||||
var sum = 0.0
|
||||
for (i in hh.indices) sum += hh[i] * lag(r, 2 * d - (i - hhRadius))
|
||||
sum
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Weight a_φ(e) of G_l(p + e) in ↑2(2h * ↓2(h * G_l))(p) for p ≡ φ (mod 2).
|
||||
* G_{l+1}(q) sits at G_l position 2q, so j = p − 2q has the parity of p.
|
||||
*/
|
||||
private fun phaseKernel(taps: DoubleArray, phase: Int): Map<Int, Double> {
|
||||
val radius = (taps.size - 1) / 2
|
||||
val kernel = HashMap<Int, Double>()
|
||||
for (j in -radius..radius) {
|
||||
if ((j - phase).mod(2) != 0) continue
|
||||
val upsample = 2.0 * taps[j + radius]
|
||||
for (i in -radius..radius) {
|
||||
val e = -j - i
|
||||
kernel[e] = (kernel[e] ?: 0.0) + upsample * taps[i + radius]
|
||||
}
|
||||
}
|
||||
return kernel
|
||||
}
|
||||
|
||||
/** Per-axis (A0, A1, A2) with Var[L] = A0x·A0y − 2·A1x·A1y + A2x·A2y. */
|
||||
private fun laplacianAxisTerms(r: DoubleArray, taps: DoubleArray, phase: Int): DoubleArray {
|
||||
val kernel = phaseKernel(taps, phase)
|
||||
var a1 = 0.0
|
||||
var a2 = 0.0
|
||||
for ((ei, wi) in kernel) {
|
||||
a1 += wi * lag(r, ei)
|
||||
for ((ej, wj) in kernel) a2 += wi * wj * lag(r, ei - ej)
|
||||
}
|
||||
return doubleArrayOf(lag(r, 0), a1, a2)
|
||||
}
|
||||
|
||||
private fun autoConvolve(taps: DoubleArray): DoubleArray {
|
||||
val out = DoubleArray(2 * taps.size - 1)
|
||||
for (i in taps.indices) {
|
||||
for (j in taps.indices) out[i + (taps.size - 1 - j)] += taps[i] * taps[j]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun lag(r: DoubleArray, d: Int): Double =
|
||||
if (d in -MAX_LAG..MAX_LAG) r[d + MAX_LAG] else 0.0
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.hinnka.mycamera.raw.denoise
|
||||
|
||||
/**
|
||||
* Noise model of docs/photon-multiscale-denoise.md §2 in normalised, un-white-balanced
|
||||
* camera RGB:
|
||||
*
|
||||
* Σ(p) = Σ_c T_c · v_c(p)
|
||||
* v_c(p) = m_r·g_c²·r_c + m_s·g_c·s_c·μ_c + q_c·μ_c²
|
||||
*
|
||||
* c indexes the CFA source channels R, G, B. μ is the signal after lens shading gain g.
|
||||
* [transfer] holds T_c (row-major 3×3, PSD): the contribution of source channel c to the
|
||||
* covariance of the RGB the denoiser receives. Spatial correlation is carried separately
|
||||
* for the luma and chroma working channels as separable 128-bin spectra (§2.1, A2).
|
||||
*
|
||||
* Every linear operation is an exact transform of this state (§2.3).
|
||||
*/
|
||||
internal class PhotonNoiseState(
|
||||
val read: DoubleArray,
|
||||
val shot: DoubleArray,
|
||||
val quadratic: DoubleArray,
|
||||
val transfer: Array<DoubleArray>,
|
||||
val lumaSpectrumX: FloatArray,
|
||||
val lumaSpectrumY: FloatArray,
|
||||
val chromaSpectrumX: FloatArray,
|
||||
val chromaSpectrumY: FloatArray,
|
||||
) {
|
||||
init {
|
||||
require(read.size == CHANNELS && shot.size == CHANNELS && quadratic.size == CHANNELS)
|
||||
require((read + shot + quadratic).all { it.isFinite() && it >= 0.0 }) {
|
||||
"Noise coefficients must be finite and non-negative"
|
||||
}
|
||||
require(transfer.size == CHANNELS && transfer.all { it.size == CHANNELS * CHANNELS })
|
||||
require(transfer.all { matrix -> isSymmetricPsdDiagonal(matrix) }) {
|
||||
"Transfer matrices must be symmetric with a non-negative diagonal"
|
||||
}
|
||||
listOf(lumaSpectrumX, lumaSpectrumY, chromaSpectrumX, chromaSpectrumY).forEach { spectrum ->
|
||||
require(spectrum.size == PhotonNoisePropagation.SPECTRUM_SIZE)
|
||||
require(spectrum.all { it.isFinite() && it >= 0f })
|
||||
}
|
||||
}
|
||||
|
||||
/** v_c of §2.1 for one location. */
|
||||
fun sourceVariance(
|
||||
mu: DoubleArray,
|
||||
gain: DoubleArray = UNIT_GAIN,
|
||||
mergeRead: Double = 1.0,
|
||||
mergeShot: Double = 1.0,
|
||||
): DoubleArray {
|
||||
require(mu.size == CHANNELS && gain.size == CHANNELS)
|
||||
return DoubleArray(CHANNELS) { c ->
|
||||
mergeRead * gain[c] * gain[c] * read[c] +
|
||||
mergeShot * gain[c] * shot[c] * mu[c] +
|
||||
quadratic[c] * mu[c] * mu[c]
|
||||
}
|
||||
}
|
||||
|
||||
/** T'_c = (K·M·W) T_c (K·M·W)ᵀ in the working YCbCr domain (§5.3). */
|
||||
fun workingTransfer(whiteBalance: DoubleArray, scale: Double): Array<DoubleArray> {
|
||||
require(whiteBalance.size == CHANNELS && whiteBalance.all { it.isFinite() && it > 0.0 })
|
||||
require(scale.isFinite() && scale > 0.0)
|
||||
val a = DoubleArray(CHANNELS * CHANNELS) { index ->
|
||||
scale * YCC_FROM_RGB[index] * whiteBalance[index % CHANNELS]
|
||||
}
|
||||
return Array(CHANNELS) { c -> congruence(a, transfer[c]) }
|
||||
}
|
||||
|
||||
/** Point covariance Σ(p) of working YCbCr, row-major 3×3. */
|
||||
fun workingCovariance(
|
||||
muCamera: DoubleArray,
|
||||
whiteBalance: DoubleArray,
|
||||
scale: Double,
|
||||
gain: DoubleArray = UNIT_GAIN,
|
||||
mergeRead: Double = 1.0,
|
||||
mergeShot: Double = 1.0,
|
||||
): DoubleArray {
|
||||
val variance = sourceVariance(muCamera, gain, mergeRead, mergeShot)
|
||||
val working = workingTransfer(whiteBalance, scale)
|
||||
return DoubleArray(CHANNELS * CHANNELS) { index ->
|
||||
var sum = 0.0
|
||||
for (c in 0 until CHANNELS) sum += variance[c] * working[c][index]
|
||||
sum
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val CHANNELS = 3
|
||||
private val UNIT_GAIN = doubleArrayOf(1.0, 1.0, 1.0)
|
||||
|
||||
/** Working YCbCr: Y = (R + 2G + B)/4, Cb = B − G, Cr = R − G (§5.1). */
|
||||
val YCC_FROM_RGB = doubleArrayOf(
|
||||
0.25, 0.5, 0.25,
|
||||
0.0, -1.0, 1.0,
|
||||
1.0, -1.0, 0.0,
|
||||
)
|
||||
|
||||
/** Exact inverse of [YCC_FROM_RGB]. */
|
||||
val RGB_FROM_YCC = doubleArrayOf(
|
||||
1.0, -0.25, 0.75,
|
||||
1.0, -0.25, -0.25,
|
||||
1.0, 0.75, -0.25,
|
||||
)
|
||||
|
||||
/** T_c of a channel-preserving source (Sabre RGB merge, §3.2): e_c e_cᵀ. */
|
||||
fun diagonalTransfer(): Array<DoubleArray> = Array(CHANNELS) { c ->
|
||||
DoubleArray(CHANNELS * CHANNELS) { index -> if (index == c * CHANNELS + c) 1.0 else 0.0 }
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapses canonical R, Gr, Gb, B Bayer coefficients onto the three source channels.
|
||||
* Both green sites pass through a symmetric demosaic transfer, so averaging their
|
||||
* variance contributions is exact (§3.1).
|
||||
*/
|
||||
fun sourceCoefficientsFromBayer(canonicalRggb: FloatArray): DoubleArray {
|
||||
require(canonicalRggb.size == 4)
|
||||
return doubleArrayOf(
|
||||
canonicalRggb[0].toDouble(),
|
||||
0.5 * (canonicalRggb[1].toDouble() + canonicalRggb[2].toDouble()),
|
||||
canonicalRggb[3].toDouble(),
|
||||
)
|
||||
}
|
||||
|
||||
fun unitSpectrum(): FloatArray = FloatArray(PhotonNoisePropagation.SPECTRUM_SIZE) { 1f }
|
||||
|
||||
private fun congruence(a: DoubleArray, t: DoubleArray): DoubleArray {
|
||||
val at = DoubleArray(CHANNELS * CHANNELS)
|
||||
for (i in 0 until CHANNELS) {
|
||||
for (k in 0 until CHANNELS) {
|
||||
var sum = 0.0
|
||||
for (j in 0 until CHANNELS) sum += a[i * CHANNELS + j] * t[j * CHANNELS + k]
|
||||
at[i * CHANNELS + k] = sum
|
||||
}
|
||||
}
|
||||
return DoubleArray(CHANNELS * CHANNELS) { index ->
|
||||
val i = index / CHANNELS
|
||||
val l = index % CHANNELS
|
||||
var sum = 0.0
|
||||
for (k in 0 until CHANNELS) sum += at[i * CHANNELS + k] * a[l * CHANNELS + k]
|
||||
sum
|
||||
}
|
||||
}
|
||||
|
||||
private fun isSymmetricPsdDiagonal(matrix: DoubleArray): Boolean {
|
||||
if (matrix.any { !it.isFinite() }) return false
|
||||
for (i in 0 until CHANNELS) {
|
||||
if (matrix[i * CHANNELS + i] < 0.0) return false
|
||||
for (j in i + 1 until CHANNELS) {
|
||||
val a = matrix[i * CHANNELS + j]
|
||||
val b = matrix[j * CHANNELS + i]
|
||||
if (kotlin.math.abs(a - b) > 1e-9 * (1.0 + kotlin.math.abs(a))) return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -226,22 +226,29 @@ internal data class CaptureDenoiseStrengths(
|
||||
val bakedChroma: Float?,
|
||||
)
|
||||
|
||||
/**
|
||||
* RAW captures take the RAWmax luma / chroma strengths from the settings. A merge bakes them into
|
||||
* its default denoise before the DNG is written, so its editable strengths start at 0; a single
|
||||
* frame has no default denoise, so the same strengths become its editable initial values and the
|
||||
* user-adjustment denoise applies them (docs/photon-multiscale-denoise.md §10.3).
|
||||
*/
|
||||
internal fun resolveCaptureDenoiseStrengths(
|
||||
isRawCapture: Boolean,
|
||||
isMergedCapture: Boolean,
|
||||
userPrefs: UserPreferences?,
|
||||
): CaptureDenoiseStrengths = when {
|
||||
!isRawCapture -> CaptureDenoiseStrengths(0f, 0f, null, null)
|
||||
else -> CaptureDenoiseStrengths(
|
||||
editableLuma = 0f,
|
||||
editableChroma = 0f,
|
||||
bakedLuma = RawDenoiseDefaults.normalize(
|
||||
userPrefs?.rawMaxNoiseReduction ?: RawDenoiseDefaults.RAW_MAX_LUMA_STRENGTH
|
||||
),
|
||||
bakedChroma = RawDenoiseDefaults.normalize(
|
||||
userPrefs?.rawMaxChromaNoiseReduction
|
||||
?: RawDenoiseDefaults.RAW_MAX_CHROMA_STRENGTH
|
||||
),
|
||||
): CaptureDenoiseStrengths {
|
||||
if (!isRawCapture) return CaptureDenoiseStrengths(0f, 0f, null, null)
|
||||
val luma = RawDenoiseDefaults.normalize(
|
||||
userPrefs?.rawMaxNoiseReduction ?: RawDenoiseDefaults.RAW_MAX_LUMA_STRENGTH
|
||||
)
|
||||
val chroma = RawDenoiseDefaults.normalize(
|
||||
userPrefs?.rawMaxChromaNoiseReduction ?: RawDenoiseDefaults.RAW_MAX_CHROMA_STRENGTH
|
||||
)
|
||||
return if (isMergedCapture) {
|
||||
CaptureDenoiseStrengths(editableLuma = 0f, editableChroma = 0f, bakedLuma = luma, bakedChroma = chroma)
|
||||
} else {
|
||||
CaptureDenoiseStrengths(editableLuma = luma, editableChroma = chroma, bakedLuma = null, bakedChroma = null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun ColorRecipeParams.withoutIndependentEffects(): ColorRecipeParams {
|
||||
@@ -6044,6 +6051,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
)
|
||||
val denoiseStrengths = resolveCaptureDenoiseStrengths(
|
||||
isRawCapture = isRawCapture,
|
||||
isMergedCapture = false,
|
||||
userPrefs = userPrefs,
|
||||
)
|
||||
val noiseReductionValue = denoiseStrengths.editableLuma
|
||||
@@ -6450,6 +6458,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
)
|
||||
val denoiseStrengths = resolveCaptureDenoiseStrengths(
|
||||
isRawCapture = isRawStack,
|
||||
isMergedCapture = true,
|
||||
userPrefs = userPrefs,
|
||||
)
|
||||
val noiseReductionValue = denoiseStrengths.editableLuma
|
||||
@@ -6811,6 +6820,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
)
|
||||
val denoiseStrengths = resolveCaptureDenoiseStrengths(
|
||||
isRawCapture = isRawCapture,
|
||||
isMergedCapture = true,
|
||||
userPrefs = userPrefs,
|
||||
)
|
||||
val noiseReductionValue = denoiseStrengths.editableLuma
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
package com.hinnka.mycamera.lut
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ChromaDenoiseShadersTest {
|
||||
@Test
|
||||
fun rawOpponentValuesStayInOneLinearCameraRgbDomain() {
|
||||
val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE
|
||||
|
||||
assertTrue(shader.contains("rgb.r - rgb.g"))
|
||||
assertTrue(shader.contains("rgb.b - rgb.g"))
|
||||
assertTrue(shader.contains("(rgb.r + rgb.g + rgb.b) / 3.0"))
|
||||
assertTrue(shader.contains("value.x - (value.y + value.z) / 3.0"))
|
||||
assertTrue(shader.contains("green + value.y"))
|
||||
assertTrue(shader.contains("green + value.z"))
|
||||
assertFalse(shader.contains("cameraChromaScale"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rawNeighborMeanIsNormalizedBackToTheCenterSignal() {
|
||||
val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE
|
||||
|
||||
assertTrue(shader.contains("sumSignal += sampleValue.x * weight"))
|
||||
assertTrue(shader.contains("centerSignal / max(averageSignal, 1e-6)"))
|
||||
assertTrue(shader.contains("averageChroma * signalScale"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rawOpponentAndGuideBandwidthsIncludeGreenNoise() {
|
||||
val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE
|
||||
|
||||
assertTrue(shader.contains("uniform vec2 uNoiseModelG;"))
|
||||
assertTrue(shader.contains("variance.rb + variance.gg"))
|
||||
assertTrue(shader.contains("variance.r + variance.g + variance.b"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyScaleUsesTheSameBoundedChromaEdgeThreshold() {
|
||||
val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE
|
||||
|
||||
assertTrue(shader.contains("exp(-chromaDistance)"))
|
||||
assertTrue(shader.contains("float chromaEdgeSigmaMultiplier"))
|
||||
assertFalse(shader.contains("signalSnr"))
|
||||
assertFalse(shader.contains("cloudRadius"))
|
||||
assertFalse(shader.contains("vec2 cloudH"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rawCameraRgbUsesSymmetricLuminanceInsteadOfGreenGuide() {
|
||||
val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE
|
||||
|
||||
assertTrue(shader.contains("texture(uGuideTexture, sampleCoord).r - centerGuide"))
|
||||
assertTrue(ChromaDenoiseShaders.PASS_EDGE_GUIDE.contains(
|
||||
"(rgb.r + rgb.g + rgb.b) / 3.0"
|
||||
))
|
||||
assertFalse(ChromaDenoiseShaders.PASS_EDGE_GUIDE.contains("return rgb.g"))
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class MgcSabreMergedNoiseModelTest {
|
||||
@Test
|
||||
fun identicalFramesFollowClassicSnrCurveAndInverseFrameCount() {
|
||||
val frame = MgcSabreMergedNoiseModel.Frame(
|
||||
floatArrayOf(0.001f, 0.002f, 0.003f),
|
||||
floatArrayOf(0.01f, 0.02f, 0.03f),
|
||||
)
|
||||
for ((snr, correction) in listOf(0f to 0.8f, 0.5f to 0.8f,
|
||||
2.25f to 0.9f, 4f to 1f, 7f to 0.85f, 10f to 0.7f, 30f to 0.7f)) {
|
||||
for (count in listOf(1, 2, 3, 8)) {
|
||||
val output = MgcSabreMergedNoiseModel.merge(List(count) { frame }, snr, 1f)
|
||||
assertArrayEquals(FloatArray(3) { frame.read[it] * correction / count },
|
||||
output.read, 1e-9f)
|
||||
assertArrayEquals(FloatArray(3) { frame.shot[it] * correction / count },
|
||||
output.shot, 1e-8f)
|
||||
assertArrayEquals(FloatArray(128) { 1f }, output.correlation, 0f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun heterogeneousExposureNormalizedFramesRetainBothNoiseModels() {
|
||||
// Frame 2 has already been transported by gain=2: read*4, shot*2.
|
||||
// Independent equal-weight averaging yields (model1 + model2)/4 at SNR=4.
|
||||
val output = MgcSabreMergedNoiseModel.merge(listOf(
|
||||
MgcSabreMergedNoiseModel.Frame(
|
||||
floatArrayOf(0.001f, 0.002f, 0.004f),
|
||||
floatArrayOf(0.01f, 0.02f, 0.04f),
|
||||
),
|
||||
MgcSabreMergedNoiseModel.Frame(
|
||||
floatArrayOf(0.008f, 0.024f, 0.032f),
|
||||
floatArrayOf(0.06f, 0.08f, 0.16f),
|
||||
),
|
||||
), 4f, 1f)
|
||||
assertArrayEquals(floatArrayOf(0.00225f, 0.0065f, 0.009f), output.read, 1e-9f)
|
||||
assertArrayEquals(floatArrayOf(0.0175f, 0.025f, 0.05f), output.shot, 1e-8f)
|
||||
assertEquals(0.2f / kotlin.math.sqrt(0.0115f),
|
||||
MgcSpatialMergeTuning.outputNoiseModelSnr(0.2f, output.read[1], output.shot[1])!!,
|
||||
1e-6f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun constructorSeedChangesOnlySpectrumAndSurvivesFrameComposition() {
|
||||
val frame = MgcSabreMergedNoiseModel.Frame(
|
||||
floatArrayOf(0.001f, 0.002f, 0.003f),
|
||||
floatArrayOf(0.01f, 0.02f, 0.03f),
|
||||
)
|
||||
for (count in listOf(1, 3, 8)) {
|
||||
val frames = List(count) { frame }
|
||||
val classic = MgcSabreMergedNoiseModel.merge(frames, 20f, 1f)
|
||||
val configured = MgcSabreMergedNoiseModel.merge(
|
||||
frames, 20f, PhotonDenoiseTuning(noiseSpectrumSeed = 0.5f).noiseSpectrumSeed,
|
||||
)
|
||||
assertArrayEquals(classic.read, configured.read, 0f)
|
||||
assertArrayEquals(classic.shot, configured.shot, 0f)
|
||||
assertArrayEquals(FloatArray(128) { 0.5f }, configured.correlation, 0f)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -99,13 +99,4 @@ class MgcSabreNoiseEstimatesLutTest {
|
||||
assertTrue(shader.contains(sqrtTransform))
|
||||
assertTrue(shader.indexOf(sqrtTransform) < shader.indexOf(greenTensorInput))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun diagnosticMergeFactorUsesActualGreenRbfWeightsInQ8Domain() {
|
||||
val shader = GlesMgcRawSabreShaders.reciprocalGreenWeight4x4
|
||||
|
||||
assertTrue(shader.contains("texelFetch(uAccumulatedWeightsGb, p, 0).r"))
|
||||
assertTrue(shader.contains("floor(weight * 256.0 + 0.5)"))
|
||||
assertTrue(shader.contains("reciprocalSum += 256.0 / weightQ8"))
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class MgcSpatialDenoiseModelTest {
|
||||
@Test
|
||||
fun negligibleGreenDiagnosticRatioProducesIdentitySpectrum() {
|
||||
val result = checkNotNull(
|
||||
MgcSpatialDenoiseModel.fromBayerDiagnostics(
|
||||
outputWeightsSumTotalDiag0 = floatArrayOf(4f, 100f, 8f),
|
||||
outputWeightsSumTotalDiag1 = floatArrayOf(1f, 0.02f, 2f),
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(0.00005f, result.diagnosticRatio, 1e-8f)
|
||||
assertEquals(0f, result.outerTap, 0f)
|
||||
assertEquals(1f, result.centerTap, 0f)
|
||||
result.correlation.forEach { assertEquals(1f, it, 0f) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ratioJustAboveIdentityThresholdKeepsFiniteCorrelation() {
|
||||
val result = checkNotNull(
|
||||
MgcSpatialDenoiseModel.fromBayerDiagnostics(
|
||||
outputWeightsSumTotalDiag0 = floatArrayOf(6.97281f, 13.9472f, 6.97281f),
|
||||
outputWeightsSumTotalDiag1 = floatArrayOf(0f, 0.00577806f, 0f),
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(0.00010357025f, result.diagnosticRatio, 1e-10f)
|
||||
assertTrue(result.outerTap > 0f)
|
||||
assertTrue(result.centerTap > 0f)
|
||||
assertEquals(1.0, result.correlation.average(), 1e-6)
|
||||
assertTrue(result.correlation.all { it.isFinite() && it >= 0f })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun savannahFitUsesGreenDiagnosticsAndNormalizesPowerSpectrum() {
|
||||
val nullableResult =
|
||||
MgcSpatialDenoiseModel.fromBayerDiagnostics(
|
||||
outputWeightsSumTotalDiag0 = floatArrayOf(1f, 100f, 1f),
|
||||
outputWeightsSumTotalDiag1 = floatArrayOf(0f, 40f, 0f),
|
||||
)
|
||||
assertNotNull(nullableResult)
|
||||
val result = checkNotNull(nullableResult)
|
||||
|
||||
assertEquals(0.1f, result.diagnosticRatio, 1e-7f)
|
||||
assertEquals(0.1227826f, result.outerTap, 2e-6f)
|
||||
assertEquals(0.7755716f, result.centerTap, 2e-6f)
|
||||
assertEquals(1.0, result.correlation.average(), 1e-6)
|
||||
assertTrue(result.correlation.all { it.isFinite() && it >= 0f })
|
||||
for (index in 0 until 64) {
|
||||
assertEquals(
|
||||
result.correlation[index],
|
||||
result.correlation[127 - index],
|
||||
2e-6f,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun redAndBlueDiagnosticsDoNotAffectBayerSavannahFit() {
|
||||
val expected = checkNotNull(
|
||||
MgcSpatialDenoiseModel.fromBayerDiagnostics(
|
||||
outputWeightsSumTotalDiag0 = floatArrayOf(1f, 100f, 1f),
|
||||
outputWeightsSumTotalDiag1 = floatArrayOf(0f, 40f, 0f),
|
||||
),
|
||||
)
|
||||
val actual = checkNotNull(
|
||||
MgcSpatialDenoiseModel.fromBayerDiagnostics(
|
||||
outputWeightsSumTotalDiag0 = floatArrayOf(500f, 100f, 700f),
|
||||
outputWeightsSumTotalDiag1 = floatArrayOf(300f, 40f, 600f),
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(expected.diagnosticRatio, actual.diagnosticRatio, 0f)
|
||||
expected.correlation.indices.forEach { index ->
|
||||
assertEquals(expected.correlation[index], actual.correlation[index], 0f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun malformedDiagnosticsAreRejected() {
|
||||
assertEquals(
|
||||
null,
|
||||
MgcSpatialDenoiseModel.fromBayerDiagnostics(
|
||||
outputWeightsSumTotalDiag0 = floatArrayOf(1f, 2f),
|
||||
outputWeightsSumTotalDiag1 = floatArrayOf(1f, 2f, 3f),
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
null,
|
||||
MgcSpatialDenoiseModel.fromBayerDiagnostics(
|
||||
outputWeightsSumTotalDiag0 =
|
||||
floatArrayOf(1f, Float.NaN, 3f),
|
||||
outputWeightsSumTotalDiag1 = floatArrayOf(1f, 2f, 3f),
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
null,
|
||||
MgcSpatialDenoiseModel.fromBayerDiagnostics(
|
||||
outputWeightsSumTotalDiag0 = floatArrayOf(1f, 2f, 3f),
|
||||
outputWeightsSumTotalDiag1 = floatArrayOf(1f, -1f, 3f),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.max
|
||||
import kotlin.math.sin
|
||||
|
||||
class DemosaicNoiseSpectrumTest {
|
||||
@Test
|
||||
fun propagationPreservesInputAmplitudeWithoutChangingNormalizedShape() {
|
||||
val size = DemosaicNoiseSpectrum.SIZE
|
||||
val residuals = arrayOf(FloatArray(size * size) { index ->
|
||||
sin(index * 0.071).toFloat() + cos(index / size * 0.113).toFloat()
|
||||
})
|
||||
val input = FloatArray(size) { 0.5f + it.toFloat() / (size - 1) }
|
||||
val unitMean = requireNotNull(DemosaicNoiseSpectrum.propagatedCorrelation(
|
||||
residuals, intArrayOf(0), input,
|
||||
))
|
||||
assertEquals(1.0, unitMean.average(), 1e-6)
|
||||
for (amplitude in listOf(0f, 0.5f, 2f)) {
|
||||
val propagated = requireNotNull(DemosaicNoiseSpectrum.propagatedCorrelation(
|
||||
residuals, intArrayOf(0), FloatArray(size) { input[it] * amplitude },
|
||||
))
|
||||
assertEquals(amplitude.toDouble(), propagated.average(), 1e-6)
|
||||
assertArrayEquals(FloatArray(size) { unitMean[it] * amplitude }, propagated, 1e-6f)
|
||||
}
|
||||
assertNull(DemosaicNoiseSpectrum.propagatedCorrelation(
|
||||
residuals, intArrayOf(0), FloatArray(size) { Float.NaN },
|
||||
))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun halfBinFftMatchesLegacyDirectTransform() {
|
||||
val size = DemosaicNoiseSpectrum.SIZE
|
||||
val residuals = Array(3) { channel ->
|
||||
FloatArray(size * size) { index ->
|
||||
val x = index % size
|
||||
val y = index / size
|
||||
(
|
||||
sin((x + 1) * (channel + 2) * 0.071) +
|
||||
cos((y + 3) * (channel + 1) * 0.113) +
|
||||
0.15 * sin((x + y + 5) * 0.037)
|
||||
).toFloat()
|
||||
}
|
||||
}
|
||||
val channels = intArrayOf(0, 2)
|
||||
|
||||
val expected = legacyDirectPower(residuals, channels)
|
||||
val actual = DemosaicNoiseSpectrum.halfBinDirectionalPower(residuals, channels)
|
||||
|
||||
for (bin in 0 until size) {
|
||||
val tolerance = max(1e-10, abs(expected[bin]) * 1e-9)
|
||||
assertEquals("bin=$bin", expected[bin], actual[bin], tolerance)
|
||||
}
|
||||
}
|
||||
|
||||
private fun legacyDirectPower(
|
||||
residuals: Array<FloatArray>,
|
||||
channels: IntArray,
|
||||
): DoubleArray {
|
||||
val size = DemosaicNoiseSpectrum.SIZE
|
||||
val power = DoubleArray(size)
|
||||
for (bin in 0 until size) {
|
||||
val omega = (bin + 0.5) * 2.0 * PI / size - PI
|
||||
var accumulatedPower = 0.0
|
||||
for (channel in channels) {
|
||||
val residual = residuals[channel]
|
||||
for (line in 0 until size) {
|
||||
var horizontalReal = 0.0
|
||||
var horizontalImaginary = 0.0
|
||||
var verticalReal = 0.0
|
||||
var verticalImaginary = 0.0
|
||||
for (position in 0 until size) {
|
||||
val real = cos(omega * position)
|
||||
val imaginary = sin(omega * position)
|
||||
val horizontal = residual[line * size + position]
|
||||
val vertical = residual[position * size + line]
|
||||
horizontalReal += horizontal * real
|
||||
horizontalImaginary -= horizontal * imaginary
|
||||
verticalReal += vertical * real
|
||||
verticalImaginary -= vertical * imaginary
|
||||
}
|
||||
accumulatedPower +=
|
||||
horizontalReal * horizontalReal +
|
||||
horizontalImaginary * horizontalImaginary +
|
||||
verticalReal * verticalReal +
|
||||
verticalImaginary * verticalImaginary
|
||||
}
|
||||
}
|
||||
power[bin] = accumulatedPower / (2.0 * size * size)
|
||||
}
|
||||
return power
|
||||
}
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.processor.PhotonPyramidScales
|
||||
import com.hinnka.mycamera.processor.PhotonPyramidOverrides
|
||||
import com.hinnka.mycamera.processor.PhotonDenoiseTuning
|
||||
import com.hinnka.mycamera.processor.PhotonSabreLumaTuningNodes
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class MgcFullResolutionDenoiseTest {
|
||||
// Historical fixture for native interpolation; deliberately independent of runtime defaults.
|
||||
private val agcP0Fixture = run {
|
||||
// Audited p0 A/B controls: A fills levels 1–4, B fills level 5.
|
||||
val strengthScale = PhotonPyramidScales(2.5f, 2.5f, 2.5f, 2.5f, 1.25f)
|
||||
val revertScale = PhotonPyramidScales.uniform(2f)
|
||||
val outlierScale = PhotonPyramidScales.uniform(0.75f)
|
||||
val strengthNodes = PhotonSabreLumaTuningNodes(
|
||||
snr5 = PhotonPyramidOverrides(0.60f, 0.45f, 0.30f, 0.15f, 0.15f),
|
||||
snr20 = PhotonPyramidOverrides(0.35f, 0.20f, 0.10f, 0.50f, 0f),
|
||||
snr40 = PhotonPyramidOverrides(0.65f, 0.35f, 0.35f, 0.20f, 0.05f),
|
||||
)
|
||||
val revertNodes = PhotonSabreLumaTuningNodes(
|
||||
// The protobuf's fifth layer has no revert field. AGC's L5A is outlier.
|
||||
snr5 = PhotonPyramidOverrides(-1f, -1f, -1f, 0f, null),
|
||||
snr20 = PhotonPyramidOverrides(-1f, -1f, 0f, -1f, null),
|
||||
snr40 = PhotonPyramidOverrides(0f, 0f, 0f, 0f, null),
|
||||
)
|
||||
val outlierNodes = PhotonSabreLumaTuningNodes(
|
||||
snr5 = PhotonPyramidOverrides(0.05f, 0f, 0f, 0.05f, 0f),
|
||||
snr20 = PhotonPyramidOverrides(0.05f, -1f, 0f, 0f, -1f),
|
||||
snr40 = PhotonPyramidOverrides(0f, 0.05f, 0f, 0f, 0f),
|
||||
)
|
||||
|
||||
PhotonDenoiseTuning(
|
||||
lumaStrengthScale = strengthScale,
|
||||
detailReconstructionScale = revertScale,
|
||||
outlierRejectionScale = outlierScale,
|
||||
sabreLumaNodes = strengthNodes,
|
||||
sabreLumaRevertNodes = revertNodes,
|
||||
sabreLumaOutlierNodes = outlierNodes,
|
||||
).normalized()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun p0NodeLookupAndInterpolationMatchOriginalArm64Bits() {
|
||||
val rows = requireNotNull(javaClass.getResourceAsStream(
|
||||
"/noise_profiles/agc96_p0_luma_interpolation.csv",
|
||||
)).bufferedReader().use { it.readLines().drop(1) }
|
||||
assertEquals(180, rows.size)
|
||||
val points = p0Points()
|
||||
for (line in rows) {
|
||||
val row = line.split(',')
|
||||
val snr = Float.fromBits(row[0].toLong(16).toInt())
|
||||
val actual = MgcFullResolutionDenoise.interpolateTuning(snr, points)
|
||||
val values = when (row[1]) {
|
||||
"strength" -> actual.strength
|
||||
"revert" -> actual.revertFactor
|
||||
"outlier" -> actual.outlierDistance
|
||||
else -> error(line)
|
||||
}
|
||||
assertEquals(line, row[3].toLong(16).toInt(), values[row[2].toInt()].toRawBits())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun p0OverridesAllSnrNodesAndPreservesSignedFieldsThroughScaling() {
|
||||
val expectedStrength = listOf(
|
||||
floatArrayOf(1.5f, 1.125f, 0.75f, 0.375f, 0.1875f),
|
||||
floatArrayOf(0.875f, 0.5f, 0.25f, 1.25f, 0f),
|
||||
floatArrayOf(1.625f, 0.875f, 0.875f, 0.5f, 0.0625f),
|
||||
)
|
||||
val expectedRevert = listOf(
|
||||
floatArrayOf(-2f, -2f, -2f, 0f, 0f),
|
||||
floatArrayOf(-2f, -2f, 0f, -2f, 0f),
|
||||
floatArrayOf(0f, 0f, 0f, 0f, 0f),
|
||||
)
|
||||
val expectedOutlier = listOf(
|
||||
floatArrayOf(0.0375f, 0f, 0f, 0.0375f, 0f),
|
||||
floatArrayOf(0.0375f, -0.75f, 0f, 0f, -0.75f),
|
||||
floatArrayOf(0f, 0.0375f, 0f, 0f, 0f),
|
||||
)
|
||||
p0Points().forEachIndexed { index, point ->
|
||||
val actual = scaleP0(point.tuning)
|
||||
assertArrayEquals(expectedStrength[index], actual.strength, 1e-7f)
|
||||
assertArrayEquals(expectedRevert[index], actual.revertFactor, 0f)
|
||||
assertArrayEquals(expectedOutlier[index], actual.outlierDistance, 1e-7f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun p0InterpolatesSignedFieldsBeforeMultipliersAndClampsOutsideSnrRange() {
|
||||
val points = p0Points()
|
||||
fun at(snr: Float) = scaleP0(MgcFullResolutionDenoise.interpolateTuning(snr, points))
|
||||
val lowMid = at(12.5f)
|
||||
assertArrayEquals(floatArrayOf(1.1875f, 0.8125f, 0.5f, 0.8125f, 0.09375f), lowMid.strength, 2e-7f)
|
||||
assertArrayEquals(floatArrayOf(-2f, -2f, -1f, -1f, 0f), lowMid.revertFactor, 0f)
|
||||
assertArrayEquals(floatArrayOf(0.0375f, -0.375f, 0f, 0.01875f, -0.375f), lowMid.outlierDistance, 1e-7f)
|
||||
val highMid = at(30f)
|
||||
assertArrayEquals(floatArrayOf(1.25f, 0.6875f, 0.5625f, 0.875f, 0.03125f), highMid.strength, 2e-7f)
|
||||
assertArrayEquals(floatArrayOf(-1f, -1f, 0f, -1f, 0f), highMid.revertFactor, 0f)
|
||||
assertArrayEquals(floatArrayOf(0.01875f, -0.35625f, 0f, 0f, -0.375f), highMid.outlierDistance, 1e-7f)
|
||||
assertArrayEquals(at(5f).strength, at(0f).strength, 0f)
|
||||
assertArrayEquals(at(40f).strength, at(60f).strength, 0f)
|
||||
// Interpolating cannot modify the stored nodes for the next frame.
|
||||
assertArrayEquals(floatArrayOf(-1f, -1f, -1f, 0f, 0f), points[0].tuning.revertFactor, 0f)
|
||||
}
|
||||
|
||||
private fun p0Points(): List<MgcFullResolutionDenoise.TuningPoint> {
|
||||
val defaults = agcP0Fixture
|
||||
return listOf(5f, 20f, 40f).map { snr ->
|
||||
MgcFullResolutionDenoise.TuningPoint(
|
||||
snr,
|
||||
MgcFullResolutionDenoise.applySabreLumaNodeOverrides(
|
||||
tuning = MgcFullResolutionDenoise.Tuning(FloatArray(5) { 9f }, FloatArray(5), FloatArray(5) { 9f }),
|
||||
snr = snr,
|
||||
nodes = defaults.sabreLumaNodes,
|
||||
revertNodes = defaults.sabreLumaRevertNodes,
|
||||
outlierNodes = defaults.sabreLumaOutlierNodes,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun scaleP0(tuning: MgcFullResolutionDenoise.Tuning): MgcFullResolutionDenoise.Tuning {
|
||||
val defaults = agcP0Fixture
|
||||
return MgcFullResolutionDenoise.applyCoreDenoiseScales(
|
||||
tuning = tuning,
|
||||
globalStrengthScale = 1f,
|
||||
strengthLevelScales = defaults.lumaStrengthScale.toFloatArray(),
|
||||
revertLevelScales = defaults.detailReconstructionScale.toFloatArray(),
|
||||
outlierLevelScales = defaults.outlierRejectionScale.toFloatArray(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun userAdjustmentNoiseModelMapsCamera2CfaPhasesToCanonicalRgb() {
|
||||
val metadata = metadata(
|
||||
cfaPattern = RawMetadata.CFA_BGGR,
|
||||
noiseProfileLayout = RawNoiseProfileLayout.CAMERA2_CFA,
|
||||
channelNoiseProfile = floatArrayOf(
|
||||
8f, 80f,
|
||||
4f, 40f,
|
||||
2f, 20f,
|
||||
1f, 10f,
|
||||
),
|
||||
)
|
||||
|
||||
val noise = requireNotNull(
|
||||
MgcFullResolutionDenoise.resolveUserAdjustmentCameraRgbNoise(metadata),
|
||||
)
|
||||
|
||||
assertArrayEquals(floatArrayOf(10f, 30f, 80f), noise.read, 0f)
|
||||
assertArrayEquals(floatArrayOf(1f, 3f, 8f), noise.shot, 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun userAdjustmentNoiseModelRejectsIncompleteCanonicalProfile() {
|
||||
val metadata = metadata(
|
||||
cfaPattern = RawMetadata.CFA_RGGB,
|
||||
noiseProfileLayout = RawNoiseProfileLayout.CANONICAL_BAYER,
|
||||
channelNoiseProfile = floatArrayOf(1f, 10f, 2f, 20f, 4f, 40f),
|
||||
)
|
||||
|
||||
assertNull(MgcFullResolutionDenoise.resolveUserAdjustmentCameraRgbNoise(metadata))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun lumaStrengthScalesChangeOnlyFiveLevelStrengthFields() {
|
||||
val original = MgcFullResolutionDenoise.Tuning(
|
||||
strength = floatArrayOf(1f, 2f, 3f, 4f, 5f),
|
||||
revertFactor = floatArrayOf(6f, 7f, 8f, 9f, 10f),
|
||||
outlierDistance = floatArrayOf(11f, 12f, 13f, 14f, 15f),
|
||||
)
|
||||
|
||||
val patched = MgcFullResolutionDenoise.applyLumaStrengthScales(
|
||||
tuning = original,
|
||||
globalScale = 0.5f,
|
||||
levelScales = floatArrayOf(2f, 2f, 2f, 2f, 3f),
|
||||
)
|
||||
|
||||
assertArrayEquals(floatArrayOf(1f, 2f, 3f, 4f, 7.5f), patched.strength, 0f)
|
||||
assertArrayEquals(original.revertFactor, patched.revertFactor, 0f)
|
||||
assertArrayEquals(original.outlierDistance, patched.outlierDistance, 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun denoiseDomainsMultiplyTheirIndependentProtoFields() {
|
||||
val original = MgcFullResolutionDenoise.Tuning(
|
||||
strength = floatArrayOf(1f, 2f, 3f, 4f, 5f),
|
||||
revertFactor = floatArrayOf(2f, 3f, 4f, 5f, 6f),
|
||||
outlierDistance = floatArrayOf(3f, 4f, 5f, 6f, 7f),
|
||||
)
|
||||
|
||||
val patched = MgcFullResolutionDenoise.applyCoreDenoiseScales(
|
||||
tuning = original,
|
||||
globalStrengthScale = 0.5f,
|
||||
strengthLevelScales = floatArrayOf(2f, 2f, 2f, 2f, 3f),
|
||||
revertLevelScales = floatArrayOf(0.25f, 0.25f, 0.25f, 0.25f, 0.5f),
|
||||
outlierLevelScales = floatArrayOf(4f, 4f, 4f, 4f, 5f),
|
||||
)
|
||||
|
||||
assertArrayEquals(floatArrayOf(1f, 2f, 3f, 4f, 7.5f), patched.strength, 0f)
|
||||
assertArrayEquals(floatArrayOf(0.5f, 0.75f, 1f, 1.25f, 3f), patched.revertFactor, 0f)
|
||||
assertArrayEquals(floatArrayOf(12f, 16f, 20f, 24f, 35f), patched.outlierDistance, 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sabreLumaOverridesReplaceTuningNodeBeforeInterpolation() {
|
||||
val original = MgcFullResolutionDenoise.Tuning(
|
||||
strength = floatArrayOf(1f, 2f, 3f, 4f, 5f),
|
||||
revertFactor = FloatArray(5) { 6f },
|
||||
outlierDistance = FloatArray(5) { 7f },
|
||||
)
|
||||
val nodes = PhotonSabreLumaTuningNodes(
|
||||
snr5 = PhotonPyramidOverrides(0.8f, null, 0.5f, null, 0.7f),
|
||||
)
|
||||
|
||||
val patched = MgcFullResolutionDenoise.applySabreLumaNodeOverrides(
|
||||
tuning = original,
|
||||
snr = PhotonSabreLumaTuningNodes.SNR_5,
|
||||
nodes = nodes,
|
||||
)
|
||||
|
||||
assertArrayEquals(floatArrayOf(0.8f, 2f, 0.5f, 4f, 0.7f), patched.strength, 0f)
|
||||
assertArrayEquals(original.revertFactor, patched.revertFactor, 0f)
|
||||
assertArrayEquals(original.outlierDistance, patched.outlierDistance, 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fusionCorrelationControlScalesSpectrumNotNoiseCoefficients() {
|
||||
val identity = MgcFullResolutionDenoise.applyFusionCorrelationScale(
|
||||
correlation = null,
|
||||
scale = 0.5f,
|
||||
enabled = true,
|
||||
)
|
||||
assertArrayEquals(FloatArray(128) { 0.5f }, requireNotNull(identity), 0f)
|
||||
|
||||
val untouched = FloatArray(128) { 2f }
|
||||
assertArrayEquals(
|
||||
untouched,
|
||||
requireNotNull(
|
||||
MgcFullResolutionDenoise.applyFusionCorrelationScale(
|
||||
correlation = untouched,
|
||||
scale = 0.5f,
|
||||
enabled = false,
|
||||
),
|
||||
),
|
||||
0f,
|
||||
)
|
||||
}
|
||||
|
||||
private fun metadata(
|
||||
cfaPattern: Int,
|
||||
noiseProfileLayout: RawNoiseProfileLayout,
|
||||
channelNoiseProfile: FloatArray,
|
||||
): RawMetadata = RawMetadata(
|
||||
width = 64,
|
||||
height = 64,
|
||||
cfaPattern = cfaPattern,
|
||||
blackLevel = FloatArray(4),
|
||||
whiteLevel = 65535f,
|
||||
whiteBalanceGains = FloatArray(4) { 1f },
|
||||
colorCorrectionMatrix = floatArrayOf(
|
||||
1f, 0f, 0f,
|
||||
0f, 1f, 0f,
|
||||
0f, 0f, 1f,
|
||||
),
|
||||
channelNoiseProfile = channelNoiseProfile,
|
||||
noiseProfileLayout = noiseProfileLayout,
|
||||
)
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class MgcSpatialStrengthMapTest {
|
||||
@Test
|
||||
fun partialRawCellsUseIdentityWithoutRescalingValidAotSamples() {
|
||||
val values = shortArrayOf(37, 129, 411, 87, 303, 902)
|
||||
val native = MgcSpatialStrengthMap(3, 2, values)
|
||||
val covered = native.withIdentityBorder(fullWidth = 14, fullHeight = 10)
|
||||
|
||||
assertEquals(4, covered.width)
|
||||
assertEquals(3, covered.height)
|
||||
assertArrayEquals(
|
||||
shortArrayOf(37, 129, 411, 256, 87, 303, 902, 256, 256, 256, 256, 256),
|
||||
covered.q8,
|
||||
)
|
||||
assertArrayEquals(values, native.q8)
|
||||
assertSame(native, native.withIdentityBorder(fullWidth = 12, fullHeight = 8))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun identityMapUsesQuarterResolutionQ8Defaults() {
|
||||
val strengthMap = MgcSpatialStrengthMap.identityForFullResolution(
|
||||
fullWidth = 4033,
|
||||
fullHeight = 3025,
|
||||
)
|
||||
|
||||
assertEquals(1009, strengthMap.width)
|
||||
assertEquals(757, strengthMap.height)
|
||||
assertEquals(strengthMap.width * strengthMap.height, strengthMap.q8.size)
|
||||
assertTrue(strengthMap.q8.all { it.toInt() == 256 })
|
||||
}
|
||||
}
|
||||
@@ -178,113 +178,4 @@ class RawNoiseProfileSelectionTest {
|
||||
0f,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun denoiseProfileShaderUsesCameraDomainSignalScaleInsteadOfWhiteBalanceScale() {
|
||||
val shader = DenoiseProfileShaders.PRECONDITION_V2 + DenoiseProfileShaders.FINISH_V2
|
||||
|
||||
assertTrue(shader.contains("uniform vec4 uSignalScale;"))
|
||||
assertTrue(shader.contains("pixel / uSignalScale"))
|
||||
assertTrue(shader.contains("px *= uSignalScale"))
|
||||
assertFalse(shader.contains("uWb"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nlmSearchOffsetsCoverSymmetricWindowExactlyOnce() {
|
||||
val radius = DenoiseProfileShaders.SEARCH_RADIUS
|
||||
val candidates = buildList {
|
||||
DenoiseProfileNlmConfig.buildSearchOffsets(radius).forEach { q ->
|
||||
add(q.x to q.y)
|
||||
if (q.x != 0 || q.y != 0) {
|
||||
add(-q.x to -q.y)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val windowWidth = 2 * radius + 1
|
||||
assertEquals(windowWidth * windowWidth, candidates.size)
|
||||
assertEquals(candidates.size, candidates.toSet().size)
|
||||
assertTrue(candidates.all { (x, y) -> x in -radius..radius && y in -radius..radius })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nlmWeightTuningSubtractsVarianceStabilizedNoiseFloor() {
|
||||
val tuning = DenoiseProfileNlmConfig.weightTuning(
|
||||
DenoiseProfileShaders.PATCH_RADIUS
|
||||
)
|
||||
|
||||
assertEquals(54f, tuning.expectedFineDistance, 0f)
|
||||
assertEquals(2.53125f, tuning.expectedGuideDistance, 1e-6f)
|
||||
assertEquals(1f / 54f, tuning.inverseBandwidth, 1e-7f)
|
||||
assertEquals(8f, tuning.coarseGuideWeight, 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nlmShaderUsesCoarseGuideAndExplicitNoiseFloor() {
|
||||
val shader = DenoiseProfileShaders.PRECONDITION_V2 +
|
||||
DenoiseProfileShaders.FUSED_ACCU +
|
||||
DenoiseProfileShaders.FINISH_V2
|
||||
|
||||
assertTrue(shader.contains("t.a = guide"))
|
||||
assertTrue(shader.contains("uExpectedFineDistance"))
|
||||
assertTrue(shader.contains("uExpectedGuideDistance"))
|
||||
assertTrue(shader.contains("uCoarseGuideWeight"))
|
||||
assertTrue(shader.contains("uDenoiseMix"))
|
||||
assertFalse(shader.contains("distacc * uNorm - 2.0"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun zeroBiasBacktransformExactlyPreservesAnUnchangedDarkSample() {
|
||||
val input = 0.003f
|
||||
val signalScale = 0.38f
|
||||
val a = 0.0089f
|
||||
val b = 3.55e-7f
|
||||
val p = 0.62f
|
||||
val transformed = 2f * max(input / signalScale + b, 0f).pow(1f - p / 2f) /
|
||||
((2f - p) * sqrt(a))
|
||||
|
||||
val delta = transformed * transformed + DenoiseProfileShaders.BLACK_PRESERVING_BIAS
|
||||
val denominator = 4f / (sqrt(a) * (2f - p))
|
||||
val z1 = (transformed + sqrt(max(delta, 0f))) / denominator
|
||||
val restored = max(z1.pow(1f / (1f - p / 2f)) - b, 0f) * signalScale
|
||||
|
||||
assertEquals(0f, DenoiseProfileShaders.BLACK_PRESERVING_BIAS, 0f)
|
||||
assertEquals(input, restored, 1e-6f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fiftyMegapixelNlmAccumulatorIsSplitIntoBoundedStripes() {
|
||||
val width = 6144
|
||||
val height = 8192
|
||||
val maxSsboBytes = 128L * 1024L * 1024L
|
||||
|
||||
val capacityRows = DenoiseProfileStripePlanner.capacityRows(
|
||||
imageWidth = width,
|
||||
imageHeight = height,
|
||||
maxShaderStorageBlockBytes = maxSsboBytes,
|
||||
)
|
||||
val stripes = DenoiseProfileStripePlanner.plan(height, capacityRows)
|
||||
|
||||
assertEquals(256, capacityRows)
|
||||
assertEquals(32, stripes.size)
|
||||
assertEquals(
|
||||
24L * 1024L * 1024L,
|
||||
DenoiseProfileStripePlanner.requiredBytes(width, capacityRows),
|
||||
)
|
||||
assertEquals(0, stripes.first().rowOffset)
|
||||
assertEquals(height, stripes.last().rowOffset + stripes.last().rowCount)
|
||||
stripes.zipWithNext().forEach { (left, right) ->
|
||||
assertEquals(left.rowOffset + left.rowCount, right.rowOffset)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nlmStripeShaderKeepsSamplingInFullImageCoordinates() {
|
||||
val shader = DenoiseProfileShaders.FUSED_ACCU + DenoiseProfileShaders.FINISH_V2
|
||||
|
||||
assertTrue(shader.contains("uStripeRowOffset"))
|
||||
assertTrue(shader.contains("coord = stripeCoord + ivec2(0, uStripeRowOffset)"))
|
||||
assertTrue(shader.contains("stripeCoord.y * uImageSize.x + stripeCoord.x"))
|
||||
assertFalse(shader.contains("pixelIndex(coord, uImageSize)"))
|
||||
}
|
||||
}
|
||||
@@ -8,22 +8,24 @@ import org.junit.Test
|
||||
|
||||
class CaptureDenoiseStrengthsTest {
|
||||
@Test
|
||||
fun singleRawUsesHdrPlusDefaultsAndBakesThem() {
|
||||
fun singleRawStartsEditableAtRawMaxDefaults() {
|
||||
val resolved = resolveCaptureDenoiseStrengths(
|
||||
isRawCapture = true,
|
||||
isMergedCapture = false,
|
||||
userPrefs = null,
|
||||
)
|
||||
|
||||
assertEquals(0f, resolved.editableLuma, 0f)
|
||||
assertEquals(0f, resolved.editableChroma, 0f)
|
||||
assertEquals(RawDenoiseDefaults.RAW_MAX_LUMA_STRENGTH, resolved.bakedLuma ?: -1f, 0f)
|
||||
assertEquals(RawDenoiseDefaults.RAW_MAX_CHROMA_STRENGTH, resolved.bakedChroma ?: -1f, 0f)
|
||||
assertEquals(RawDenoiseDefaults.RAW_MAX_LUMA_STRENGTH, resolved.editableLuma, 0f)
|
||||
assertEquals(RawDenoiseDefaults.RAW_MAX_CHROMA_STRENGTH, resolved.editableChroma, 0f)
|
||||
assertNull(resolved.bakedLuma)
|
||||
assertNull(resolved.bakedChroma)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rawMaxDefaultsAreBakedAndGalleryAdjustmentStartsAtZero() {
|
||||
val resolved = resolveCaptureDenoiseStrengths(
|
||||
isRawCapture = true,
|
||||
isMergedCapture = true,
|
||||
userPrefs = UserPreferences(
|
||||
rawMaxNoiseReduction = 1.4f,
|
||||
rawMaxChromaNoiseReduction = 1.6f,
|
||||
@@ -40,6 +42,7 @@ class CaptureDenoiseStrengthsTest {
|
||||
fun nonRawCaptureDoesNotInheritRawDenoise() {
|
||||
val resolved = resolveCaptureDenoiseStrengths(
|
||||
isRawCapture = false,
|
||||
isMergedCapture = false,
|
||||
userPrefs = UserPreferences(
|
||||
rawMaxNoiseReduction = 1f,
|
||||
rawMaxChromaNoiseReduction = 1f,
|
||||
|
||||
Reference in new issue
Block a user