feat: configurable sharpening tuning and quality preset

This commit is contained in:
zhoubinjia committed 2026-09-16 15:24:43 +08:00
1 parent 0bf02ba5b4
commit bfbc2bf194
19 files changed
+628 -158

No files matched your search

@@ -1777,111 +1777,6 @@ int RunYuvToRgb(
return function(nullptr, &input_buffer, &output_buffer);
}
bool BuildDefaultSharpenCurves(
float snr,
const float interpolation_scales[3],
SharpenCurveSelection* output) {
if (output == nullptr || interpolation_scales == nullptr ||
!std::isfinite(snr) || snr <= 0.0f ||
!std::all_of(
interpolation_scales,
interpolation_scales + 3,
[](float value) { return std::isfinite(value); })) {
return false;
}
std::fill_n(output->relative_corner_acutance_correction, 3, 0.0f);
struct Node {
float snr;
float parameters[3][5];
};
// Decoded mechanically from MGC 9.6.080's generic
// sharpen_default.binarypb asset. BuildForSNR converts each node to
// piecewise points first, then interpolates those converted points.
constexpr Node nodes[] = {
{5.0f, {{1.6f, 0.05f, 1.0f, 1.0f, 0.0f},
{1.8f, 0.03f, 1.0f, 1.0f, 0.0f},
{1.2f, 0.02f, 1.0f, 1.0f, 0.0f}}},
{10.0f, {{2.5f, 0.05f, 1.0f, 1.0f, 0.0f},
{2.2f, 0.03f, 1.0f, 1.0f, 0.0f},
{1.3f, 0.02f, 1.0f, 1.0f, 0.0f}}},
{20.0f, {{3.2f, 0.05f, 1.0f, 1.0f, 0.0f},
{2.6f, 0.03f, 1.0f, 1.0f, 0.0f},
{1.4f, 0.02f, 1.0f, 1.0f, 0.0f}}},
{40.0f, {{5.2f, 0.02f, 1.0f, 1.0f, 0.0f},
{2.1f, 0.02f, 1.0f, 1.0f, 0.0f},
{1.4f, 0.02f, 1.0f, 1.0f, 0.0f}}},
{80.0f, {{4.7f, 0.02f, 1.0f, 1.0f, 0.0f},
{2.1f, 0.02f, 1.0f, 1.0f, 0.0f},
{1.4f, 0.02f, 1.0f, 1.0f, 0.0f}}},
};
const Node* lower = &nodes[0];
const Node* upper = &nodes[0];
if (snr >= nodes[std::size(nodes) - 1].snr) {
lower = upper = &nodes[std::size(nodes) - 1];
} else if (snr > nodes[0].snr) {
for (size_t index = 1; index < std::size(nodes); ++index) {
if (snr <= nodes[index].snr) {
lower = &nodes[index - 1];
upper = &nodes[index];
break;
}
}
}
const float interpolation = lower == upper
? 0.0f
: (snr - lower->snr) / (upper->snr - lower->snr);
const auto convert = [](const float parameters[5], float points[2][5]) {
const float gain = parameters[0];
const float first_x = parameters[1];
const float second_x = parameters[2];
const float transition_width = parameters[3];
const float transition_mix = parameters[4];
points[0][0] = 0.0f;
points[1][0] = 0.0f;
points[0][1] = first_x;
const float initial_gain = gain >= 1.0f
? std::max(gain * 0.5f, 1.0f)
: std::min(gain * 2.0f, 1.0f);
points[1][1] = initial_gain * first_x;
points[0][2] = second_x;
points[1][2] = gain * second_x;
points[0][3] = second_x + transition_width;
points[1][3] =
transition_mix *
((gain * second_x - second_x) +
(second_x + transition_width)) +
(second_x + transition_width) * (1.0f - transition_mix);
points[0][4] = points[0][3] + 1.0f;
points[1][4] = points[1][3] + 1.0f;
};
for (int frequency = 0; frequency < 3; ++frequency) {
// Photon exposes one independent interpolation scale per sharpening frequency group.
const float frequency_interpolation =
interpolation * interpolation_scales[frequency];
float lower_points[2][5] = {};
float upper_points[2][5] = {};
convert(lower->parameters[frequency], lower_points);
convert(upper->parameters[frequency], upper_points);
for (int coordinate = 0; coordinate < 2; ++coordinate) {
for (int point = 0; point < 5; ++point) {
const float lower_value = lower_points[coordinate][point];
const float upper_value = upper_points[coordinate][point];
output->curves[
point + 5 * frequency + 15 * coordinate] =
lower_value * (1.0f - frequency_interpolation) +
upper_value * frequency_interpolation;
}
}
}
output->lower_snr = lower->snr;
output->upper_snr = upper->snr;
output->interpolation = interpolation;
return true;
}
int RunSharpenTo16Bit(
const int16_t* input_yuv,
int width,
@@ -37,17 +37,6 @@ struct SpatialStrengthResult {
float output_weights_sum_total_diag_1[3] = {};
};
struct SharpenCurveSelection {
float lower_snr = 0.0f;
float upper_snr = 0.0f;
float interpolation = 0.0f;
// Halide layout [guide=1, point=5, frequency=3, coordinate=2].
float curves[30] = {};
// Optional CurveParams field, one value per sharpening frequency. The
// generic sharpen_default.binarypb profile leaves all three unset.
float relative_corner_acutance_correction[3] = {};
};
/**
* Reproduces CreateLumaDenoiseNoiseBuffers for one luma noise channel.
* correlation is MGC's 128-bin normalized power correlation spectrum. A
@@ -222,15 +211,6 @@ int RunYuvToRgb(
int height,
int16_t* output);
/**
* Reproduces SharpenTuning::BuildForSNR for MGC's generic
* sharpen_default.binarypb profile.
*/
bool BuildDefaultSharpenCurves(
float snr,
const float interpolation_scales[3],
SharpenCurveSelection* output);
/**
* Runs MGC 9.6.080's exact SharpenTo16BitHalide FinishRaw kernel.
*
@@ -102,9 +102,9 @@ void SharpenRgbToRgba(const uint16_t *rgb, size_t count, uint8_t *rgba) {
extern "C" JNIEXPORT jint JNICALL
Java_com_hinnka_mycamera_raw_MgcSharpen_nativeSharpenRgba8(
JNIEnv *env, jobject, jobject rgba_buffer, jobject scratch_buffer,
jint width, jint height, jfloat snr, jfloat attenuation) {
jint width, jint height, jfloat snr, jfloat attenuation, jfloatArray curve_points) {
using namespace photon::mgc_denoise;
if (!rgba_buffer || !scratch_buffer || width <= 0 || height <= 0 ||
if (!rgba_buffer || !scratch_buffer || !curve_points || width <= 0 || height <= 0 ||
!std::isfinite(snr) || snr <= 0 || !std::isfinite(attenuation) ||
attenuation < 0)
return -1;
@@ -122,17 +122,31 @@ Java_com_hinnka_mycamera_raw_MgcSharpen_nativeSharpenRgba8(
env->GetDirectBufferCapacity(scratch_buffer) < jlong(scratch_bytes))
return -1;
auto *rgb = reinterpret_cast<uint16_t *>(yuv + count * 3);
SharpenCurveSelection curves;
constexpr float scales[3] = {1, 1, 1};
if (!BuildDefaultSharpenCurves(snr, scales, &curves))
// Curves are resolved once in Kotlin from Photon's local, named tuning table.
// Halide layout: point + 5 * frequency + 15 * coordinate.
if (env->GetArrayLength(curve_points) != 30)
return -1;
float curves[30];
env->GetFloatArrayRegion(curve_points, 0, 30, curves);
if (env->ExceptionCheck())
return -1;
for (int band = 0; band < 3; ++band) {
for (int point = 0; point < 5; ++point) {
const int index = point + 5 * band;
const float x = curves[index], y = curves[index + 15];
if (!std::isfinite(x) || !std::isfinite(y) || x < 0 || y < 0 ||
(point == 0 && (x != 0 || y != 0)) ||
(point > 0 && x <= curves[index - 1]))
return -1;
}
}
constexpr float corner_correction[3] = {0, 0, 0};
using Clock = std::chrono::steady_clock;
const auto start = Clock::now();
SharpenRgbaToYuv(rgba, count, yuv);
const auto converted = Clock::now();
const int result = RunSharpenTo16Bit(
yuv, width, height, curves.curves,
curves.relative_corner_acutance_correction, attenuation, rgb);
yuv, width, height, curves, corner_correction, attenuation, rgb);
if (result != 0)
return result;
const auto sharpened = Clock::now();
@@ -2244,6 +2244,8 @@ object GalleryManager {
captureExposureCompensationEv = captureExposureCompensationEv,
).let(physicalRawCrop::rebase).copy(
exposureCompensation = captureExposureCompensationEv,
rawMaxQualityTuningEnabled =
PhotonSensorSizeTuning.enabledFromProperties(metadata.customProperties),
rawMaxQualityTuningSensorAreaMm2 =
PhotonSensorSizeTuning.areaFromProperties(metadata.customProperties),
)
@@ -2375,6 +2377,8 @@ object GalleryManager {
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
rawCustomWhiteLevel = updatedMetadata.rawCustomWhiteLevel,
sharpeningValue = rawSharpening,
processLocalQualityTuningEnabled =
PhotonSensorSizeTuning.enabledFromProperties(updatedMetadata.customProperties),
processLocalQualityTuningSensorAreaMm2 =
PhotonSensorSizeTuning.areaFromProperties(updatedMetadata.customProperties),
denoiseValue = rawNoiseReduction,
@@ -2466,6 +2470,8 @@ object GalleryManager {
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
rawCustomWhiteLevel = updatedMetadata.rawCustomWhiteLevel,
sharpeningValue = rawSharpening,
processLocalQualityTuningEnabled =
PhotonSensorSizeTuning.enabledFromProperties(updatedMetadata.customProperties),
processLocalQualityTuningSensorAreaMm2 =
PhotonSensorSizeTuning.areaFromProperties(updatedMetadata.customProperties),
denoiseValue = rawNoiseReduction,
@@ -3260,6 +3266,8 @@ object GalleryManager {
colorSpace = RawDemosaicProcessor.getInstance().getRawColorSpace(),
).let(physicalRawCrop::rebase).copy(
exposureCompensation = captureExposureCompensationEv,
rawMaxQualityTuningEnabled =
PhotonSensorSizeTuning.enabledFromProperties(metadata.customProperties),
rawMaxQualityTuningSensorAreaMm2 =
PhotonSensorSizeTuning.areaFromProperties(metadata.customProperties),
)
@@ -3711,6 +3719,8 @@ object GalleryManager {
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
rawCustomWhiteLevel = updatedMetadata.rawCustomWhiteLevel,
sharpeningValue = rawSharpening,
processLocalQualityTuningEnabled =
PhotonSensorSizeTuning.enabledFromProperties(updatedMetadata.customProperties),
processLocalQualityTuningSensorAreaMm2 =
PhotonSensorSizeTuning.areaFromProperties(updatedMetadata.customProperties),
processLocalMgcSharpenTuningSnr = finalStackResult.mgcSharpenTuningSnr,
@@ -3803,6 +3813,8 @@ object GalleryManager {
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
rawCustomWhiteLevel = updatedMetadata.rawCustomWhiteLevel,
sharpeningValue = rawSharpening,
processLocalQualityTuningEnabled =
PhotonSensorSizeTuning.enabledFromProperties(updatedMetadata.customProperties),
processLocalQualityTuningSensorAreaMm2 =
PhotonSensorSizeTuning.areaFromProperties(updatedMetadata.customProperties),
denoiseValue = rawNoiseReduction,
@@ -4084,6 +4096,8 @@ object GalleryManager {
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
rawCustomWhiteLevel = updatedMetadata.rawCustomWhiteLevel,
sharpeningValue = rawSharpening,
processLocalQualityTuningEnabled =
PhotonSensorSizeTuning.enabledFromProperties(updatedMetadata.customProperties),
processLocalQualityTuningSensorAreaMm2 =
PhotonSensorSizeTuning.areaFromProperties(updatedMetadata.customProperties),
denoiseValue = rawNoiseReduction,
@@ -5533,6 +5547,8 @@ object GalleryManager {
rawWhiteLevelMode = updatedMetadata.rawWhiteLevelMode,
rawCustomWhiteLevel = updatedMetadata.rawCustomWhiteLevel,
sharpeningValue = RawSharpeningDefaults.DEFAULT_STRENGTH,
processLocalQualityTuningEnabled =
PhotonSensorSizeTuning.enabledFromProperties(updatedMetadata.customProperties),
processLocalQualityTuningSensorAreaMm2 =
PhotonSensorSizeTuning.areaFromProperties(updatedMetadata.customProperties),
denoiseValue = rawNoiseReduction,
@@ -5707,6 +5723,8 @@ object GalleryManager {
rawCustomWhiteLevel = updatedMetadata?.rawCustomWhiteLevel,
sharpeningValue = updatedMetadata?.sharpening
?: RawSharpeningDefaults.DEFAULT_STRENGTH,
processLocalQualityTuningEnabled =
PhotonSensorSizeTuning.enabledFromProperties(updatedMetadata?.customProperties.orEmpty()),
processLocalQualityTuningSensorAreaMm2 =
PhotonSensorSizeTuning.areaFromProperties(updatedMetadata?.customProperties.orEmpty()),
denoiseValue = rawNoiseReduction,
@@ -588,6 +588,8 @@ class PhotoProcessor(
rawWhiteLevelMode = metadata.rawWhiteLevelMode,
rawCustomWhiteLevel = metadata.rawCustomWhiteLevel,
sharpeningValue = rawSharpening,
processLocalQualityTuningEnabled =
PhotonSensorSizeTuning.enabledFromProperties(metadata.customProperties),
processLocalQualityTuningSensorAreaMm2 =
PhotonSensorSizeTuning.areaFromProperties(metadata.customProperties),
denoiseValue = rawNoiseReduction,
@@ -670,6 +672,8 @@ class PhotoProcessor(
rawWhiteLevelMode = metadata.rawWhiteLevelMode,
rawCustomWhiteLevel = metadata.rawCustomWhiteLevel,
sharpeningValue = finalSharpening,
processLocalQualityTuningEnabled =
PhotonSensorSizeTuning.enabledFromProperties(metadata.customProperties),
processLocalQualityTuningSensorAreaMm2 =
PhotonSensorSizeTuning.areaFromProperties(metadata.customProperties),
denoiseValue = finalNoiseReduction,
@@ -4,6 +4,8 @@ package com.hinnka.mycamera.processor
object PhotonCoreImagingTuning {
val fusion: PhotonFusionTuning = PhotonFusionTuning.DEFAULT
val denoise: PhotonDenoiseTuning = PhotonDenoiseTuning.DEFAULT
/** Local SNR/contrast curves for the original MGC final sharpening kernel. */
val sharpen: PhotonSharpenTuning = PhotonSharpenTuning.DEFAULT
/** Dehaze + DHA baked into HDRNet's ProfileGainTableMap output. */
val dehaze: PhotonDehazeTuning = PhotonDehazeTuning.DEFAULT
}
@@ -0,0 +1,53 @@
package com.hinnka.mycamera.processor
/** Fixed quality-toggle preset, shared by every sensor and by capture/reprocessing. */
object PhotonQualitySharpenTuning {
/**
* Sabre selector 0 is clamped to 1: first table, nodes 2/8/16.
* raw A/B=1.125, depth1=0, depth2=1.375; last-node gains=10/.05/.9.
* sharpness A=.34375, B=0. No RAISR/Polysharp or denoise controls here.
*/
val FIXED = PhotonSharpenTuning(
amount = PhotonSharpenBands(.34375f, .34375f, 0f),
nodes = listOf(
PhotonSharpenSnrNode(2f,
band0 = curve(.006f, 2.5f * 1.125f),
band1 = curve(.002f, 1.8f * 1.125f),
band2 = curve(.002f, 1.2f * 1.125f)),
PhotonSharpenSnrNode(8f,
band0 = curve(.001f, 2.8f * 1.125f),
band1 = curve(.0005f, 2.1f * 1.125f),
band2 = curve(.0005f, 1.4f * 1.125f)),
PhotonSharpenSnrNode(16f,
band0 = curve(.0002f, 10f * 1.125f),
band1 = curve(.0001f, .05f * 1.125f, lowContrastGain = 2f * .05f * 1.125f),
band2 = curve(.0002f, .9f * 1.125f)),
),
)
fun resolve(enabled: Boolean): PhotonSharpenTuning =
if (enabled) FIXED else PhotonCoreImagingTuning.sharpen
private fun curve(
lowContrastInput: Float,
mainContrastGain: Float,
lowContrastGain: Float = 1.375f,
): PhotonSharpenCurve {
// Original Sabre constants at 0x6ad348: second_x=.02, width=.01.
// With transition_mix=1 and depth2=1.375 the third point is
// y3=(gain*.02-.02+x3)+x3*(1.375-1). Keep every term of that mapping.
val mainInput = .02f
val highInput = mainInput + .01f
val highOutput = (mainContrastGain * mainInput - mainInput + highInput) +
highInput * .375f
return PhotonSharpenCurve(
lowContrastInput = lowContrastInput,
lowContrastGain = lowContrastGain,
mainContrastInput = mainInput,
mainContrastGain = mainContrastGain,
highContrastInput = highInput,
highContrastGain = highOutput / highInput,
tailSpan = 1.375f,
)
}
}
@@ -37,17 +37,21 @@ object PhotonSensorSizeTuning {
changePerAreaStop = 0.033127858f,
)
/** Only the capture choice and sensor area are stored, never a core-parameter override. */
/** Capture choice survives missing area so fixed sharpening can still be selected. */
fun captureProperties(enabled: Boolean, sensorPhysicalAreaMm2: Float?): Map<String, String> {
if (!enabled) return emptyMap()
val area = sensorPhysicalAreaMm2?.takeIf { it.isFinite() && it > 0f }
return if (enabled && area != null) mapOf(
MODEL_PROPERTY to MODEL_ID,
SENSOR_AREA_PROPERTY to area.toString(),
) else emptyMap()
return buildMap {
put(MODEL_PROPERTY, MODEL_ID)
if (area != null) put(SENSOR_AREA_PROPERTY, area.toString())
}
}
fun enabledFromProperties(properties: Map<String, String>): Boolean =
properties[MODEL_PROPERTY] == MODEL_ID
fun areaFromProperties(properties: Map<String, String>): Float? =
if (properties[MODEL_PROPERTY] == MODEL_ID) {
if (enabledFromProperties(properties)) {
properties[SENSOR_AREA_PROPERTY]?.toFloatOrNull()?.takeIf { it.isFinite() && it > 0f }
} else null
@@ -0,0 +1,123 @@
package com.hinnka.mycamera.processor
/**
* Local final-sharpening defaults; no preferences or photo-metadata serialization.
* See docs/photon-sharpen-tuning.md for units, equations and editing examples.
*
* [nodes] must be ordered by reference-frame SNR, not merged-frame SNR.
* [amount] scales each interpolated curve's departure from y=x. It does not
* change SNR interpolation. The existing user slider/runtime attenuation remains
* a separate input to the original kernel.
*/
data class PhotonSharpenTuning(
val nodes: List<PhotonSharpenSnrNode>,
val amount: PhotonSharpenBands = PhotonSharpenBands(),
) {
init {
require(nodes.isNotEmpty()) { "Sharpen tuning needs at least one SNR node" }
require(nodes.zipWithNext().all { (a, b) -> a.snr < b.snr }) {
"Sharpen SNR nodes must be strictly increasing"
}
}
companion object {
/** Explicit equivalent of the previous MGC generic curve table. */
val DEFAULT = PhotonSharpenTuning(
nodes = listOf(
PhotonSharpenSnrNode(5f,
band0 = PhotonSharpenCurve(lowContrastInput = .05f, lowContrastGain = 1f, mainContrastGain = 1.6f),
band1 = PhotonSharpenCurve(lowContrastInput = .03f, lowContrastGain = 1f, mainContrastGain = 1.8f),
band2 = PhotonSharpenCurve(lowContrastInput = .02f, lowContrastGain = 1f, mainContrastGain = 1.2f)),
PhotonSharpenSnrNode(10f,
band0 = PhotonSharpenCurve(lowContrastInput = .05f, lowContrastGain = 1.25f, mainContrastGain = 2.5f),
band1 = PhotonSharpenCurve(lowContrastInput = .03f, lowContrastGain = 1.1f, mainContrastGain = 2.2f),
band2 = PhotonSharpenCurve(lowContrastInput = .02f, lowContrastGain = 1f, mainContrastGain = 1.3f)),
PhotonSharpenSnrNode(20f,
band0 = PhotonSharpenCurve(lowContrastInput = .05f, lowContrastGain = 1.6f, mainContrastGain = 3.2f),
band1 = PhotonSharpenCurve(lowContrastInput = .03f, lowContrastGain = 1.3f, mainContrastGain = 2.6f),
band2 = PhotonSharpenCurve(lowContrastInput = .02f, lowContrastGain = 1f, mainContrastGain = 1.4f)),
PhotonSharpenSnrNode(40f,
band0 = PhotonSharpenCurve(lowContrastInput = .02f, lowContrastGain = 2.6f, mainContrastGain = 5.2f),
band1 = PhotonSharpenCurve(lowContrastInput = .02f, lowContrastGain = 1.05f, mainContrastGain = 2.1f),
band2 = PhotonSharpenCurve(lowContrastInput = .02f, lowContrastGain = 1f, mainContrastGain = 1.4f)),
PhotonSharpenSnrNode(80f,
band0 = PhotonSharpenCurve(lowContrastInput = .02f, lowContrastGain = 2.35f, mainContrastGain = 4.7f),
band1 = PhotonSharpenCurve(lowContrastInput = .02f, lowContrastGain = 1.05f, mainContrastGain = 2.1f),
band2 = PhotonSharpenCurve(lowContrastInput = .02f, lowContrastGain = 1f, mainContrastGain = 1.4f)),
),
)
}
}
/**
* Dimensionless enhancement amounts, indexed exactly like the MGC frequency axis.
* 0 = identity curve, 1 = configured curve; >1 extrapolates its enhancement or
* suppression. These are frequency groups, not RGB channels or denoise levels.
*/
data class PhotonSharpenBands(val band0: Float = 1f, val band1: Float = 1f, val band2: Float = 1f) {
init {
require(listOf(band0, band1, band2).all { it.isFinite() && it >= 0f })
}
operator fun get(band: Int): Float = when (band) {
0 -> band0
1 -> band1
2 -> band2
else -> error("Invalid sharpening frequency index: $band")
}
}
/** One positive, linear reference SNR and one contrast curve per native frequency group. */
data class PhotonSharpenSnrNode(
val snr: Float,
val band0: PhotonSharpenCurve,
val band1: PhotonSharpenCurve,
val band2: PhotonSharpenCurve,
) {
init { require(snr.isFinite() && snr > 0f) }
operator fun get(band: Int): PhotonSharpenCurve = when (band) {
0 -> band0
1 -> band1
2 -> band2
else -> error("Invalid sharpening frequency index: $band")
}
}
/**
* Five-point response: origin, three explicit contrast knots, then a unit-slope tail.
* Input coordinates are in the MGC response-curve domain, NOT pixel radius,
* scene brightness or an ISO value. Gains are output/input at each knot;
* only [lowContrastGain] is also the slope from the origin.
*
* The high-contrast gain may be smaller than the main gain (roll-off). Output
* knots therefore need not be monotonic. Input knots must always increase.
*/
data class PhotonSharpenCurve(
/** First knot x; marks the end of the initial constant-gain segment. */
val lowContrastInput: Float = .02f,
/** Gain throughout the segment from zero to lowContrastInput. */
val lowContrastGain: Float = 1f,
/** Second knot x; center of the configurable contrast enhancement. */
val mainContrastInput: Float = 1f,
/** Second knot y/x, not a multiplier of the other gains. */
val mainContrastGain: Float = 1f,
/** Third knot x; end of the transition from the main gain to the high gain. */
val highContrastInput: Float = 2f,
/** Third knot y/x; 1 rejoins identity at this knot, >1 retains enhancement. */
val highContrastGain: Float = 1f,
/** x span to the final knot; y increases by the same span (slope exactly 1). */
val tailSpan: Float = 1f,
) {
init {
require(listOf(lowContrastInput, mainContrastInput, highContrastInput, tailSpan)
.all { it.isFinite() && it > 0f })
require(lowContrastInput < mainContrastInput && mainContrastInput < highContrastInput)
require(listOf(lowContrastGain, mainContrastGain, highContrastGain)
.all { it.isFinite() && it >= 0f })
require((lowContrastInput * lowContrastGain).isFinite())
require((mainContrastInput * mainContrastGain).isFinite())
require((highContrastInput * highContrastGain + tailSpan).isFinite())
require((highContrastInput + tailSpan).isFinite() && highContrastInput + tailSpan > highContrastInput)
}
}
@@ -3,6 +3,8 @@ package com.hinnka.mycamera.raw
import android.opengl.GLES30
import android.opengl.GLES31
import com.hinnka.mycamera.processor.GlesGpuCompletion
import com.hinnka.mycamera.processor.PhotonCoreImagingTuning
import com.hinnka.mycamera.processor.PhotonSharpenTuning
import com.hinnka.mycamera.utils.LargeDirectBuffer
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
@@ -25,9 +27,11 @@ internal class MgcSharpen {
height: Int,
snr: Float,
attenuation: Float,
tuning: PhotonSharpenTuning = PhotonCoreImagingTuning.sharpen,
) {
require(width > 0 && height > 0 && snr.isFinite() && snr > 0f)
require(attenuation.isFinite() && attenuation >= 0f)
val curves = MgcSharpenCurveBuilder.build(snr, tuning)
val pixels = width.toLong() * height
val outputPixels = width.toLong() * ((height.toLong() + 1) and -2L)
val scratchBytes = (pixels + outputPixels) * 6
@@ -70,7 +74,7 @@ internal class MgcSharpen {
val nativeStart = System.nanoTime()
try {
val result = nativeSharpenRgba8(mapped.order(ByteOrder.nativeOrder()),
checkNotNull(scratch), width, height, snr, attenuation)
checkNotNull(scratch), width, height, snr, attenuation, curves.points)
check(result == 0) { "MGC original sharpen failed: $result" }
} finally {
check(GLES30.glUnmapBuffer(GLES30.GL_PIXEL_PACK_BUFFER)) {
@@ -85,6 +89,8 @@ internal class MgcSharpen {
}
PLog.i(TAG, "originalMgc=true size=${width}x$height referenceSnr=$snr " +
"attenuation=$attenuation transfer=${if (useCompute) "SSBO" else "PBO"} " +
"curveSnr=${curves.lowerSnr}:${curves.upperSnr} curveMix=${curves.interpolation} " +
"bandAmount=${tuning.amount} mainGains=${curves.mainGains} " +
"allocationMs=$allocationMs upstreamGpuWaitMs=$upstreamWaitMs " +
"transferAndMapMs=$transferMs nativeAndUnmapMs=$nativeMs " +
"uploadSubmitMs=${elapsedMs(uploadStart)} totalCpuMs=${elapsedMs(start)}")
@@ -147,6 +153,7 @@ internal class MgcSharpen {
private external fun nativeSharpenRgba8(
rgba: ByteBuffer, scratch: ByteBuffer, width: Int, height: Int, snr: Float, attenuation: Float,
curves: FloatArray,
): Int
private external fun nativeUploadRgba8(pbo: Int, texture: Int, width: Int, height: Int): Boolean
@@ -0,0 +1,64 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.processor.PhotonSharpenCurve
import com.hinnka.mycamera.processor.PhotonSharpenTuning
/** Converts Photon's named controls to the original Halide [point, frequency, coordinate] ABI. */
internal object MgcSharpenCurveBuilder {
data class Selection(
val points: FloatArray,
val lowerSnr: Float,
val upperSnr: Float,
val interpolation: Float,
) {
val mainGains: List<Float>
get() = (0..2).map { points[17 + 5 * it] / points[2 + 5 * it] }
}
fun build(snr: Float, tuning: PhotonSharpenTuning): Selection {
require(snr.isFinite() && snr > 0f)
val nodes = tuning.nodes
// Revalidate the list at the boundary: callers may have supplied a mutable List.
require(nodes.isNotEmpty() && nodes.zipWithNext().all { (a, b) -> a.snr < b.snr })
val upperIndex = nodes.indexOfFirst { it.snr >= snr }
.let { if (it < 0) nodes.lastIndex else it }
val lowerIndex = if (snr >= nodes.last().snr) nodes.lastIndex
else (upperIndex - 1).coerceAtLeast(0)
val lower = nodes[lowerIndex]
val upper = nodes[upperIndex]
val t = if (lowerIndex == upperIndex) 0f else (snr - lower.snr) / (upper.snr - lower.snr)
val result = FloatArray(30)
for (band in 0..2) {
val a = points(lower[band])
val b = points(upper[band])
val amount = tuning.amount[band]
for (point in 0..4) {
// Interpolate actual x/y points, never gains or an amount-scaled SNR fraction.
val x = a[point] * (1f - t) + b[point] * t
val y = a[point + 5] * (1f - t) + b[point + 5] * t
val adjusted = when (amount) {
0f -> x
1f -> y // Preserve the original default's Float rounding.
else -> x + amount * (y - x)
}
require(x.isFinite() && adjusted.isFinite() && adjusted >= 0f) {
"Invalid sharpen response at band=$band point=$point amount=$amount"
}
result[point + 5 * band] = x
result[point + 5 * band + 15] = adjusted
require(point == 0 || x > result[point - 1 + 5 * band]) {
"Sharpen input knots collapsed at band=$band point=$point"
}
}
}
return Selection(result, lower.snr, upper.snr, t)
}
private fun points(curve: PhotonSharpenCurve): FloatArray = with(curve) {
floatArrayOf(
0f, lowContrastInput, mainContrastInput, highContrastInput, highContrastInput + tailSpan,
0f, lowContrastInput * lowContrastGain, mainContrastInput * mainContrastGain,
highContrastInput * highContrastGain, highContrastInput * highContrastGain + tailSpan,
)
}
}
@@ -22,6 +22,7 @@ import com.hinnka.mycamera.camera.RawBlackBorderCrop
import com.hinnka.mycamera.data.ContentRepository
import com.hinnka.mycamera.lut.ChromaDenoiseAlgorithm
import com.hinnka.mycamera.ml.SharedDepthEstimator
import com.hinnka.mycamera.processor.PhotonQualitySharpenTuning
import com.hinnka.mycamera.processor.GlesGpuCompletion
import com.hinnka.mycamera.processor.GlesGpuScheduler
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
@@ -228,6 +229,7 @@ class RawDemosaicProcessor {
mgcDenoiseTuningSnr = baseMetadata?.mgcDenoiseTuningSnr,
mgcSharpenTuningSnr = baseMetadata?.mgcSharpenTuningSnr,
mgcSharpenAttenuationScale = baseMetadata?.mgcSharpenAttenuationScale,
rawMaxQualityTuningEnabled = baseMetadata?.rawMaxQualityTuningEnabled ?: false,
rawMaxQualityTuningSensorAreaMm2 = baseMetadata?.rawMaxQualityTuningSensorAreaMm2,
rotation = dngRawData.rotation,
profileGainTableMap = baseMetadata?.profileGainTableMap
@@ -1816,6 +1818,7 @@ class RawDemosaicProcessor {
rawWhiteLevelMode: String? = null,
rawCustomWhiteLevel: Float? = null,
sharpeningValue: Float = 0f,
processLocalQualityTuningEnabled: Boolean? = null,
processLocalQualityTuningSensorAreaMm2: Float? = null,
denoiseValue: Float? = null,
chromaDenoiseValue: Float? = null,
@@ -1864,6 +1867,7 @@ class RawDemosaicProcessor {
rawWhiteLevelMode = rawWhiteLevelMode,
rawCustomWhiteLevel = rawCustomWhiteLevel,
sharpeningValue = sharpeningValue,
processLocalQualityTuningEnabled = processLocalQualityTuningEnabled,
processLocalQualityTuningSensorAreaMm2 = processLocalQualityTuningSensorAreaMm2,
denoiseValue = denoiseValue,
chromaDenoiseValue = chromaDenoiseValue,
@@ -1915,6 +1919,7 @@ class RawDemosaicProcessor {
rawWhitePointCorrection: Float = 0f,
applyLensShadingCorrection: Boolean = true,
sharpeningValue: Float = 0f,
processLocalQualityTuningEnabled: Boolean? = null,
processLocalQualityTuningSensorAreaMm2: Float? = null,
denoiseValue: Float? = null,
chromaDenoiseValue: Float? = null,
@@ -1957,6 +1962,7 @@ class RawDemosaicProcessor {
rawWhitePointCorrection = rawWhitePointCorrection,
applyLensShadingCorrection = applyLensShadingCorrection,
sharpeningValue = sharpeningValue,
processLocalQualityTuningEnabled = processLocalQualityTuningEnabled,
processLocalQualityTuningSensorAreaMm2 = processLocalQualityTuningSensorAreaMm2,
denoiseValue = denoiseValue,
chromaDenoiseValue = chromaDenoiseValue,
@@ -2059,6 +2065,7 @@ class RawDemosaicProcessor {
rawWhiteLevelMode: String? = null,
rawCustomWhiteLevel: Float? = null,
sharpeningValue: Float = 0f,
processLocalQualityTuningEnabled: Boolean? = null,
processLocalQualityTuningSensorAreaMm2: Float? = null,
processLocalMgcSharpenTuningSnr: Float? = null,
processLocalMgcSharpenAttenuationScale: Float? = null,
@@ -2109,6 +2116,7 @@ class RawDemosaicProcessor {
rawWhiteLevelMode = rawWhiteLevelMode,
rawCustomWhiteLevel = rawCustomWhiteLevel,
sharpeningValue = sharpeningValue,
processLocalQualityTuningEnabled = processLocalQualityTuningEnabled,
processLocalQualityTuningSensorAreaMm2 = processLocalQualityTuningSensorAreaMm2,
processLocalMgcSharpenTuningSnr = processLocalMgcSharpenTuningSnr,
processLocalMgcSharpenAttenuationScale = processLocalMgcSharpenAttenuationScale,
@@ -2172,6 +2180,7 @@ class RawDemosaicProcessor {
rawWhiteLevelMode: String? = null,
rawCustomWhiteLevel: Float? = null,
sharpeningValue: Float = 0f,
processLocalQualityTuningEnabled: Boolean? = null,
processLocalQualityTuningSensorAreaMm2: Float? = null,
denoiseValue: Float? = null,
chromaDenoiseValue: Float? = null,
@@ -2270,6 +2279,7 @@ class RawDemosaicProcessor {
rawWhiteLevelMode = rawWhiteLevelMode,
rawCustomWhiteLevel = rawCustomWhiteLevel,
sharpeningValue = sharpeningValue,
processLocalQualityTuningEnabled = processLocalQualityTuningEnabled,
processLocalQualityTuningSensorAreaMm2 = processLocalQualityTuningSensorAreaMm2,
denoiseValue = denoiseValue,
chromaDenoiseValue = chromaDenoiseValue,
@@ -2329,6 +2339,7 @@ class RawDemosaicProcessor {
rawWhiteLevelMode: String? = null,
rawCustomWhiteLevel: Float? = null,
sharpeningValue: Float = 0f,
processLocalQualityTuningEnabled: Boolean? = null,
processLocalQualityTuningSensorAreaMm2: Float? = null,
processLocalMgcSharpenTuningSnr: Float? = null,
processLocalMgcSharpenAttenuationScale: Float? = null,
@@ -2585,6 +2596,8 @@ class RawDemosaicProcessor {
)
actualMetadata = actualMetadata?.let {
it.copy(
rawMaxQualityTuningEnabled =
processLocalQualityTuningEnabled ?: it.rawMaxQualityTuningEnabled,
rawMaxQualityTuningSensorAreaMm2 =
processLocalQualityTuningSensorAreaMm2 ?: it.rawMaxQualityTuningSensorAreaMm2,
)
@@ -7641,7 +7654,7 @@ class RawDemosaicProcessor {
stackCompletionTimeline: GpuStackCompletionTimeline? = null,
) {
val sliderValue = RawSharpeningDefaults.normalize(sharpeningValue)
val algorithmStrength = RawSharpeningDefaults.toAlgorithmStrength(sliderValue)
val algorithmStrength = RawSharpeningDefaults.toMgcStrength(sliderValue)
val runtimeAttenuation = metadata.mgcSharpenAttenuationScale?.also { attenuation ->
check(attenuation.isFinite() && attenuation >= 0f) {
"MGC sharpen attenuation is invalid: $attenuation"
@@ -7667,11 +7680,16 @@ class RawDemosaicProcessor {
height = metadata.height,
snr = snr,
attenuation = effectiveStrength,
tuning = PhotonQualitySharpenTuning.resolve(metadata.rawMaxQualityTuningEnabled),
)
} else {
// Non-MGC GPU-only sources may have no reference RAW/statistics available.
PLog.w(TAG, "Original MGC sharpen unavailable: missing reference SNR; using GLES USM")
renderSharpenPass(metadata, effectiveStrength, inputTextureId)
renderSharpenPass(
metadata,
RawSharpeningDefaults.toAlgorithmStrength(sliderValue) * runtimeAttenuation,
inputTextureId,
)
}
}
@@ -172,7 +172,9 @@ data class RawMetadata(
val maxAnalogSensitivity: Int = 0,
val shutterSpeed: Long = 0L,
val aperture: Float = FALLBACK_APERTURE_F_NUMBER,
/** Capture-scoped sensor area when RAWmax quality tuning is enabled; null uses defaults. */
/** Capture-scoped quality choice; fixed sharpening does not require sensor geometry. */
val rawMaxQualityTuningEnabled: Boolean = false,
/** Optional area for the enabled quality mode's fusion/denoise fit only. */
val rawMaxQualityTuningSensorAreaMm2: Float? = null,
/** CameraCharacteristics sensor geometry used only for adaptive noise-model estimation. */
val sensorPhysicalWidthMm: Float = 0f,
@@ -1221,6 +1223,7 @@ data class RawMetadata(
if (mgcDenoiseTuningSnr != other.mgcDenoiseTuningSnr) return false
if (mgcSharpenTuningSnr != other.mgcSharpenTuningSnr) return false
if (mgcSharpenAttenuationScale != other.mgcSharpenAttenuationScale) return false
if (rawMaxQualityTuningEnabled != other.rawMaxQualityTuningEnabled) return false
if (rawMaxQualityTuningSensorAreaMm2 != other.rawMaxQualityTuningSensorAreaMm2) return false
if (rotation != other.rotation) return false
@@ -1260,6 +1263,7 @@ data class RawMetadata(
result = 31 * result + (mgcDenoiseTuningSnr?.hashCode() ?: 0)
result = 31 * result + (mgcSharpenTuningSnr?.hashCode() ?: 0)
result = 31 * result + (mgcSharpenAttenuationScale?.hashCode() ?: 0)
result = 31 * result + rawMaxQualityTuningEnabled.hashCode()
result = 31 * result + (rawMaxQualityTuningSensorAreaMm2?.hashCode() ?: 0)
result = 31 * result + (rotation ?: 0)
return result
@@ -11,7 +11,10 @@ object RawSharpeningDefaults {
DEFAULT_STRENGTH
}
/** Maps the persisted/UI 0..1 RAW sharpening control onto the algorithm's 0..2 domain. */
/** MGC: the default UI value is unity, so 0/.4/1 map to 0/1/2.5. */
fun toMgcStrength(value: Float): Float = normalize(value) / DEFAULT_STRENGTH
/** Maps the persisted/UI 0..1 control onto the legacy GLES USM 0..2 domain. */
fun toAlgorithmStrength(value: Float): Float =
normalize(value) * ALGORITHM_STRENGTH_SCALE
}
+12 -6
View File
@@ -112,13 +112,19 @@ static void VerifyConversions() {
"U12 to U8 exact");
puts("PASS all 16777216 RGB8 colors, SIMD tails, all uint16 output values");
}
static void Sharpen(int16_t *in, uint16_t *out, int w, int h, float snr = 20) {
SharpenCurveSelection curves;
const float scales[] = {1, 1, 1};
Check(BuildDefaultSharpenCurves(snr, scales, &curves), "curves");
static void Sharpen(int16_t *in, uint16_t *out, int w, int h) {
// Frozen SNR20 generic fixture for adapter/tile/performance checks.
// Production defaults now live only in PhotonSharpenTuning; the JVM regression
// checks cover its table and SNR interpolation independently of this probe.
const float curves[] = {
0, .05f, 1, 2, 3, 0, .03f, 1, 2, 3, 0, .02f, 1, 2, 3,
0, .05f * 1.6f, 3.2f, 2, 3,
0, .03f * 1.3f, 2.6f, 2, 3,
0, .02f, 1.4f, 2, 3,
};
const float corner_correction[] = {0, 0, 0};
int rc =
RunSharpenTo16Bit(in, w, h, curves.curves,
curves.relative_corner_acutance_correction, .8f, out);
RunSharpenTo16Bit(in, w, h, curves, corner_correction, .8f, out);
if (rc)
fprintf(stderr, "kernel size=%dx%d rc=%d\n", w, h, rc);
Check(rc == 0, "kernel");
@@ -2,6 +2,8 @@ package com.hinnka.mycamera.processor
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.log2
@@ -129,8 +131,26 @@ class PhotonSensorSizeTuningTest {
assertNull(PhotonSensorSizeTuning.forSensorAreaMm2(0f))
assertEquals(PhotonSensorSizeTuning.Parameters(), PhotonSensorSizeTuning.resolve(null))
assertEquals(PhotonSensorSizeTuning.Parameters(), PhotonSensorSizeTuning.resolve(Float.NaN))
assertEquals(emptyMap<String, String>(), PhotonSensorSizeTuning.captureProperties(true, null))
assertEquals(emptyMap<String, String>(), PhotonSensorSizeTuning.captureProperties(true, Float.POSITIVE_INFINITY))
for (area in listOf(null, Float.POSITIVE_INFINITY)) {
val properties = PhotonSensorSizeTuning.captureProperties(true, area)
assertTrue(PhotonSensorSizeTuning.enabledFromProperties(properties))
assertNull(PhotonSensorSizeTuning.areaFromProperties(properties))
assertEquals(1, properties.size)
}
}
@Test
fun fixedSharpeningUsesCaptureChoiceEvenWhenSensorAreaIsMissing() {
for (area in listOf(null, Float.NaN, 0f, 1f, 20.48f, 32f, 128f, 1000f)) {
val enabled = PhotonSensorSizeTuning.captureProperties(true, area)
val disabled = PhotonSensorSizeTuning.captureProperties(false, area)
assertSame(PhotonQualitySharpenTuning.FIXED, PhotonQualitySharpenTuning.resolve(
PhotonSensorSizeTuning.enabledFromProperties(enabled),
))
assertSame(PhotonCoreImagingTuning.sharpen, PhotonQualitySharpenTuning.resolve(
PhotonSensorSizeTuning.enabledFromProperties(disabled),
))
}
}
companion object {
@@ -0,0 +1,114 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.processor.PhotonSharpenBands
import com.hinnka.mycamera.processor.PhotonSharpenCurve
import com.hinnka.mycamera.processor.PhotonSharpenSnrNode
import com.hinnka.mycamera.processor.PhotonSharpenTuning
import com.hinnka.mycamera.processor.PhotonQualitySharpenTuning
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
class MgcSharpenCurveBuilderTest {
@Test
fun qualityPresetUsesSabreDomainAndP0Slot0FrequencyAmounts() {
val tuning = PhotonQualitySharpenTuning.FIXED
assertEquals(listOf(2f, 8f, 16f), tuning.nodes.map { it.snr })
val selected = MgcSharpenCurveBuilder.build(16f, tuning)
assertEquals(.0002f, selected.points[1], 0f)
assertEquals(.02f, selected.points[2], 0f)
assertEquals(.03f, selected.points[3], 1e-8f)
assertEquals(1.405f, selected.points[4], 1e-7f)
// Patched AGC: gain=10*1.125, low gain=1.375, depth2=1.375;
// resulting y2=.225, y3=.24625, y4=1.62125, before sharpness A.
val expectedY = floatArrayOf(
0f,
.0002f + .34375f * (.000275f - .0002f),
.02f + .34375f * (.225f - .02f),
.03f + .34375f * (.24625f - .03f),
1.405f + .34375f * (1.62125f - 1.405f),
)
assertArrayEquals(expectedY, selected.points.copyOfRange(15, 20), 2e-7f)
assertEquals(.67558594f, selected.mainGains[1], 1e-6f)
// Global sharpness B=0 makes frequency 2 identity at every SNR.
for (snr in listOf(.1f, 2f, 5f, 8f, 12f, 16f, 100f)) {
val points = MgcSharpenCurveBuilder.build(snr, tuning).points
assertArrayEquals(points.copyOfRange(10, 15), points.copyOfRange(25, 30), 0f)
}
}
@Test
fun defaultSnr20PreservesOriginalNativeCurveAndHalideLayout() {
val actual = MgcSharpenCurveBuilder.build(20f, PhotonSharpenTuning.DEFAULT)
// Original MGC generic SNR20 five-point curves, x blocks followed by y blocks.
val expected = floatArrayOf(
0f, .05f, 1f, 2f, 3f, 0f, .03f, 1f, 2f, 3f, 0f, .02f, 1f, 2f, 3f,
0f, .05f * 1.6f, 3.2f, 2f, 3f,
0f, .03f * 1.3f, 2.6f, 2f, 3f,
0f, .02f, 1.4f, 2f, 3f,
)
assertArrayEquals(expected, actual.points, 0f)
}
@Test
fun snrInterpolationUsesConvertedPointsRatherThanInterpolatedGains() {
val selected = MgcSharpenCurveBuilder.build(30f, PhotonSharpenTuning.DEFAULT)
assertEquals(20f, selected.lowerSnr, 0f)
assertEquals(40f, selected.upperSnr, 0f)
assertEquals(.5f, selected.interpolation, 0f)
assertEquals(.035f, selected.points[1], 1e-8f)
assertEquals(.066f, selected.points[16], 1e-8f)
assertEquals(4.2f, selected.points[17], 1e-6f)
}
@Test
fun bandAmountWorksAtNodesBetweenNodesAndBeyondTableAndDoesNotMoveOtherBands() {
val original = PhotonSharpenTuning.DEFAULT
val adjusted = original.copy(amount = PhotonSharpenBands(.5f, 0f, 1f))
for (snr in listOf(.1f, 5f, 7.5f, 20f, 30f, 80f, 160f)) {
val baseline = MgcSharpenCurveBuilder.build(snr, original)
val actual = MgcSharpenCurveBuilder.build(snr, adjusted)
assertEquals(baseline.interpolation, actual.interpolation, 0f)
for (point in 0..4) {
val x = baseline.points[point]
val y = baseline.points[point + 15]
assertEquals(x + .5f * (y - x), actual.points[point + 15], 0f)
assertEquals(actual.points[point + 5], actual.points[point + 20], 0f)
assertEquals(baseline.points[point + 25], actual.points[point + 25], 0f)
}
assertArrayEquals(baseline.points.copyOfRange(0, 15), actual.points.copyOfRange(0, 15), 0f)
}
}
@Test
fun customContrastKnotsAndTailReachTheKernelWithoutHiddenDepthCoupling() {
val curve = PhotonSharpenCurve(
lowContrastInput = .1f, lowContrastGain = 1.5f,
mainContrastInput = .5f, mainContrastGain = 3f,
highContrastInput = 1.5f, highContrastGain = 1.25f,
tailSpan = .5f,
)
val tuning = PhotonSharpenTuning(listOf(PhotonSharpenSnrNode(10f, curve, curve, curve)))
val selected = MgcSharpenCurveBuilder.build(40f, tuning)
assertArrayEquals(floatArrayOf(0f, .1f, .5f, 1.5f, 2f), selected.points.copyOfRange(0, 5), 0f)
assertArrayEquals(floatArrayOf(0f, .15f, 1.5f, 1.875f, 2.375f), selected.points.copyOfRange(15, 20), 0f)
}
@Test
fun invalidLocalTuningIsRejectedRatherThanSilentlyClamped() {
assertThrows(IllegalArgumentException::class.java) { PhotonSharpenCurve(lowContrastInput = 1f) }
assertThrows(IllegalArgumentException::class.java) { PhotonSharpenCurve(highContrastGain = Float.NaN) }
assertThrows(IllegalArgumentException::class.java) { PhotonSharpenBands(band1 = -1f) }
assertThrows(IllegalArgumentException::class.java) { PhotonSharpenTuning(emptyList()) }
val node = PhotonSharpenTuning.DEFAULT.nodes.first()
assertThrows(IllegalArgumentException::class.java) { PhotonSharpenTuning(listOf(node, node)) }
assertThrows(IllegalArgumentException::class.java) { MgcSharpenCurveBuilder.build(0f, PhotonSharpenTuning.DEFAULT) }
val suppress = PhotonSharpenCurve(lowContrastGain = 0f)
val invalidExtrapolation = PhotonSharpenTuning(
listOf(PhotonSharpenSnrNode(5f, suppress, suppress, suppress)),
PhotonSharpenBands(2f, 2f, 2f),
)
assertThrows(IllegalArgumentException::class.java) { MgcSharpenCurveBuilder.build(5f, invalidExtrapolation) }
}
}
+12 -7
View File
@@ -2,7 +2,8 @@
`PhotonCoreImagingTuning` 保持为本地默认值单例,不提供核心参数的持久化读写。
设置 → 专业设置 → HDR+ 画质中的「HDR+ 画质调优」恢复 1.27.2.2 的传感器面积调优算法,
默认关闭;开启后仅对 HDR+(RAWmax)拍摄应用。传感器面积缺失或无效时使用默认参数。
默认关闭;开启后仅对 HDR+(RAWmax)拍摄应用。融合/降噪随传感器面积拟合,锐化使用统一固定配方。
传感器面积缺失或无效时,融合/降噪使用默认参数,固定锐化仍按开关生效。
## 本地默认值
@@ -70,8 +71,8 @@ revert/outlier 不覆盖资产节点,只应用上述倍率。用户 RAW luma/c
## 拍摄与重处理
- 开关由 `UserPreferencesRepository` 保存;拍摄时取当前镜头的物理传感器面积。
- 每张照片只保存 `photonCoreTuningModel=photon-sensor-area-v1` 和 `photonSensorPhysicalAreaMm2`
两项,用于重建启用时的调优;关闭时不写入这两项。
- 每张照片保存 `photonCoreTuningModel=photon-sensor-area-v1` 表示启用;有效面积另存
`photonSensorPhysicalAreaMm2`。面积缺失也保留启用标记,关闭时不写入这两项。
- 拍摄默认降噪通过 `RawMetadata.rawMaxQualityTuningSensorAreaMm2` 传入;DNG 重处理和回退路径
从该照片的属性恢复面积,重新计算参数,不读取当前全局开关,也不读取旧的逐字段核心参数覆盖。
- `MgcFullResolutionDenoise` 统一解析面积调优,日志记录面积、五层倍率和频率响应。
@@ -79,11 +80,15 @@ revert/outlier 不覆盖资产节点,只应用上述倍率。用户 RAW luma/c
## 锐化与除雾
画质调优不改变最终锐化参数。具备参考帧 SNR 的 RAW 使用 MGC 9.6 原版
`SharpenTo16BitHalide` 和 `sharpen_default.binarypb` 曲线;用户 sharpening 滑杆与融合
attenuation 控制其强度。锐化选择曲线使用参考帧 SNR,降噪使用融合后 SNR,两者不可混用。
画质调优开启时使用 `PhotonQualitySharpenTuning.FIXED`:参考 AGC LM v1.1 p0 镜头槽0,
所有传感器使用同一表,不参与面积拟合;仍按参考帧 SNR 在 2/8/16 节点间插值。
关闭时使用原通用表。照片重处理恢复拍摄时的开关,不读取当前全局开关。
具备参考帧 SNR 的 RAW 使用 MGC 9.6 原版
`SharpenTo16BitHalide`。`PhotonCoreImagingTuning.sharpen` 提供本地 SNR 节点、三频段增强倍率
及显式对比度控制点,关闭画质调优时默认值等效于原 `sharpen_default.binarypb` 曲线;参数含义、完整默认表及
公式见 [Photon 锐化参数表](photon-sharpen-tuning.md)。用户 sharpening 滑杆与融合 attenuation
继续控制内核外层强度。锐化选择曲线使用参考帧 SNR,降噪使用融合后 SNR,两者不可混用。
没有参考帧统计且无法访问原始 RAW 的其他 GPU 来源保留 GLES USM,并记录原因。
实现边界与实机性能验证见 [MGC 锐化](research/mgc-sharpen-performance.md)。
HDRNet Dehaze/DHA 继续使用本地默认值,独立于面积拟合。完整链路见
[Photon HDRNet Dehaze + DHA 链路](photon-dehaze-pipeline.md)。
+136
View File
@@ -0,0 +1,136 @@
# Photon 锐化参数表
本地入口:`PhotonCoreImagingTuning.sharpen`。默认表定义在
`processor/PhotonSharpenTuning.kt`,通过 `raw/MgcSharpenCurveBuilder.kt` 构造五点曲线,
经 JNI 传入原版 `SharpenTo16BitHalide`。不增加持久化读写或设置界面。
关闭画质调优时默认值保持此前 MGC 通用锐化曲线的结果。开启时使用下述固定 AGC 参考配方。
RAISR/Polysharp 和降噪参数不属于这张锐化表。
## 画质调优的固定配方
入口:`PhotonQualitySharpenTuning.FIXED`,由拍摄时保存的画质调优标记选择。
来源:`AGC9.6v5_LMv1.1_多大底机型.agc` 的 p0「清晰🏡明亮」、镜头槽0。
选取一个明确槽位供所有传感器统一使用,不平均各镜头数值,不根据面积改变参数。
没有面积信息也可生效;SNR 适配和既有锐化滑杆/runtime attenuation 继续保留。
| 固定项 | 数值 |
| --- | --- |
| SNR 节点 | `2 / 8 / 16` |
| 频段 amount | `.34375 / .34375 / 0` |
| mainContrastInput / highContrastInput | `.02 / (.02+.01)` |
| tailSpan | `1.375` |
| lowContrastGain | `1.375`,仅 SNR16 的 band1 为 `.1125` |
| SNR | lowContrastInput(band0/1/2) | mainContrastGain(band0/1/2,应用 amount 前) |
| --- | --- | --- |
| 2 | `.006 / .002 / .002` | `2.8125 / 2.025 / 1.35` |
| 8 | `.001 / .0005 / .0005` | `3.15 / 2.3625 / 1.575` |
| 16 | `.0002 / .0001 / .0002` | `11.25 / .05625 / 1.0125` |
每条曲线的高对比度点按已核实的原生公式转换:
`y3=(mainContrastGain*.02-.02+x3)+x3*.375`,`highContrastGain=y3/x3`。
这里包含 raw A/B=1.125、depth1=0、depth2=1.375、sharp_mini=10、sabre_sharp=.05、
sharp_big=.9 的曲线作用;Sabre selector=0 最终钳为1,选第一套表。
第三频段 amount=0 后成为恒等响应,不是抹除这个频段的图像信号。
原生语义基于已有 AGC V7 库核实。Sabre 的第二横坐标和过渡宽度实际为 `.02/.01`
(0x6ad348/0x6ad34c),不能把此前通用曲线的 `1/1` 套用过来。
这是一组固定的曲线参考配方,不代表同时复现 AGC 的 RAISR/Polysharp 或整条成像链。
## 频段与数值域
- `band0/1/2` 对应原版 Halide 曲线的三个 frequency 索引。它们不是 RGB 通道,也不是五层降噪的层号。
保留原生索引,避免在尚未标定空间响应前把它们命名为某个固定像素半径。
- 曲线横轴是内核响应曲线的局部对比度坐标;不是场景明暗、曝光、ISO、噪声标准差或像素半径。
`low/main/highContrast` 指同一频段内对比度幅度由小到大,不指低/中/高空间频率。
- 增益是该控制点的输出/输入,单位为倍。`1` 表示该点不改变对比度,`>1` 增强,`0..1` 抑制。
除第一段外,控制点增益不是相邻两点间的斜率,更不是整张图的最终锐化倍数。
## 每项参数
| 参数 | 含义与调节效果 | 默认值 / 约束 |
| --- | --- | --- |
| `nodes[].snr` | 使用参考帧线性 SNR 选择曲线;节点间按 SNR 线性插值,范围外保持端点 | `5/10/20/40/80`;有限正数、严格递增,非 dB,非融合后 SNR |
| `amount.band0/1/2` | 各频段曲线相对恒等线的幅度:`y'=x+amount×(y-x)` | 全部 `1`;`0` 为恒等曲线,`>1` 放大已有增强或抑制;有限非负 |
| `lowContrastInput` | 第一控制点的横坐标,确定起始恒定增益段的结束位置 | 见下表;`0 < low < main` |
| `lowContrastGain` | 零到第一点之间的对比度增益;提高它会增强很弱的局部对比,也可能增强噪声 | 见下表;有限非负 |
| `mainContrastInput` | 第二控制点的横坐标,放置主要增强区域的位置 | `1`;`low < main < high` |
| `mainContrastGain` | 第二控制点的输出/输入比,独立于 low/high 两点的增益 | 见下表;有限非负 |
| `highContrastInput` | 第三控制点的横坐标,确定主增强向高对比度响应过渡的结束位置 | `2`;`high > main` |
| `highContrastGain` | 第三控制点的输出/输入比;`1` 在此回到恒等线,增大则保留更多强对比度增强 | `1`;有限非负 |
| `tailSpan` | 从第三点到末点的横坐标距离,纵坐标增加相同距离,尾段斜率固定为 1 | `1`;有限正数,不能因浮点舍入与前点重合 |
增大输入坐标是移动曲线分段位置,不是增大卷积半径。改变一个控制点会影响与它相邻的线段。
`highContrastGain=1` 配合默认尾段使强对比度部分回到恒等线,可限制这一段的增强;
它不保证最终图像完全没有光晕。
`amount>1` 是相对恒等线的外推。若某点原本在抑制对比度,过度外推可能生成负输出;
构造器会明确拒绝非有限值、非法节点顺序和负输出,不悄悄钳位或替换默认值。
降幅过大的曲线也可能产生明显视觉变化;检查的是输入契约,不是审美质量。
## 当前默认节点
下表每个三元组顺序均为 `band0 / band1 / band2`;每一格都是绝对值。
| 参考帧 SNR | lowContrastInput | lowContrastGain | mainContrastGain |
| --- | --- | --- | --- |
| 5 | `.05 / .03 / .02` | `1 / 1 / 1` | `1.6 / 1.8 / 1.2` |
| 10 | `.05 / .03 / .02` | `1.25 / 1.1 / 1` | `2.5 / 2.2 / 1.3` |
| 20 | `.05 / .03 / .02` | `1.6 / 1.3 / 1` | `3.2 / 2.6 / 1.4` |
| 40 | `.02 / .02 / .02` | `2.6 / 1.05 / 1` | `5.2 / 2.1 / 1.4` |
| 80 | `.02 / .02 / .02` | `2.35 / 1.05 / 1` | `4.7 / 2.1 / 1.4` |
所有节点的 `mainContrastInput=1`、`highContrastInput=2`、`highContrastGain=1`、`tailSpan=1`。
节点可增删,但必须保持 SNR 递增;只有一个节点时,对所有 SNR 使用该曲线。
## 曲线公式与生效顺序
每个频段、每个 SNR 节点先构造:
```text
P0 = (0, 0)
P1 = (lowContrastInput, lowContrastInput × lowContrastGain)
P2 = (mainContrastInput, mainContrastInput × mainContrastGain)
P3 = (highContrastInput, highContrastInput × highContrastGain)
P4 = (P3.x + tailSpan, P3.y + tailSpan)
```
先在相邻 SNR 节点的五点坐标之间插值,再对 y 应用该频段的 `amount`。
禁止把 amount 乘到 SNR 插值系数上;这样会错误地改变噪声适配,且在端点失去作用。
也不直接插值增益:当两个节点的 x 不同时,“先插值增益再乘 x”不是相同曲线。
内核仍单独接收既有的 `用户滑杆映射强度 × runtimeAttenuation`。
MGC 滑杆映射为 `normalize(value) / 0.4`:`0 → 0`、默认 `0.4 → 1`、`1 → 2.5`。
因此默认位置不额外缩放原版运行时强度;若 runtimeAttenuation 不为1,最终仍保留原版衰减。
无参考 SNR 的 GLES USM 回退继续使用其独立的 `value × 2` 映射。
这个输入与曲线参数分别生效,不能不经验证就把两者乘积宣称为最终锐化倍数。
将所有 amount 设为 0 只让曲线恒等,仍会经过内核和 RGB/YUV 数值域转换;
原有用户锐化强度为 0 的路径则直接绕过锐化处理。
## 本地调节示例
在 `PhotonCoreImagingTuning` 中修改入口即可改变拍摄与重处理默认值:
```kotlin
val sharpen = PhotonSharpenTuning.DEFAULT.copy(
amount = PhotonSharpenBands(band0 = .7f, band1 = .7f, band2 = 0f),
)
```
这会保留每个 SNR 下前两组曲线相对恒等线偏移的 70%,第三组曲线变成恒等线。
只调 SNR20 的第一频段弱对比增益,可以对该节点的 `band0.copy(lowContrastGain = ...)`
做替换;它会影响相邻的 SNR10–40 插值区间,其余频段保持不变。
日志 `PLog_MgcSharpen` 包含输入参考 SNR、选中节点 `curveSnr`、插值系数 `curveMix`、
`bandAmount`、最终第二控制点增益 `mainGains` 和既有 attenuation。
对比参数效果时固定 RAW、其他参数、输出尺寸及外层强度,再检查日志确认命中曲线节点。
## 与 AGC 参数的关系及边界
- `sharpness_a/b` 对应这里的频段 amount 作用:A 控前两组,B 控第三组;不是 SNR 插值倍率。
- 原来混杂在 `sharp_depth_1/2` 中的影响改为显式控制点、增益及 tailSpan,不保留一项同时修改多处无关常数的接口。
- AGC Sabre 表需要独立填写其实际节点和曲线。不能把 `sharp_mini=10` 直接称作全局增强10倍。
- `sharp_legibility` 属于降噪参数构造,RAISR/Polysharp 属于另外阶段,均不在本表中。
- 当前 MGC AOT 使用 Photon 编码 RGBA8 转来的 U12 YUV。参数曲线可以对齐,不能因此保证整个 AGC 成片逐像素一致。
- 没有参考 SNR 的 GPU 来源仍走原有 USM 回退,不应用这张 MGC 参数表,并记录回退原因。