diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSabreShaders.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSabreShaders.kt index 684f1cb7..6c073320 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSabreShaders.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSabreShaders.kt @@ -408,7 +408,26 @@ internal object GlesMgcRawSabreShaders { motionPrior) { robustnessBoost = uExtraMotionRobustnessBoost; } - pixelVariance *= 2.0; + // Keep the symmetric V25 bicubic guides: an identical texture must not reject + // itself. Tighten only the measured-structure allowance, not the noise floor or + // the color-difference thresholds shared with Spatial/YUV. All values here have + // already been converted from guide alpha and scaled for the bicubic filter. + float detailNoise = greenOnly + ? max(referenceNoise.y, currentNoise.y) + : max( + dot(referenceNoise, vec3(1.0 / 3.0)), + dot(currentNoise, vec3(1.0 / 3.0)) + ); + float detailConfidence = smoothstep( + ${MgcSabreRejectionTuning.SABRE_DETAIL_VARIANCE_RATIO_START} * detailNoise, + ${MgcSabreRejectionTuning.SABRE_DETAIL_VARIANCE_RATIO_END} * detailNoise, + pixelVariance + ); + pixelVariance *= mix( + 2.0, + ${MgcSabreRejectionTuning.SABRE_DETAIL_VARIANCE_SCALE}, + detailConfidence + ); vec3 combinedNoise = referenceNoise + currentNoise; vec3 difference = current.rgb - reference.rgb; vec3 differenceSquared = max( diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialStacker.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialStacker.kt index fbcf830d..9cdaddd0 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialStacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialStacker.kt @@ -2222,6 +2222,9 @@ internal class GlesMgcRawSpatialStacker( "forceReferenceColorRgb=${sabreKernelParameters.forceReferenceColorRgb} " + "mergeGradientThreshold=${PhotonCoreImagingTuning.fusion.mergeGradientThreshold ?: "adaptive"} " + "guideColorSpace=sqrt noiseLut=qmc64x10 rejectionGuideFilter=bicubic-both-frames " + + "detailVarianceScale=${MgcSabreRejectionTuning.SABRE_DETAIL_VARIANCE_SCALE} " + + "detailVarianceNoiseRatio=${MgcSabreRejectionTuning.SABRE_DETAIL_VARIANCE_RATIO_START}.." + + "${MgcSabreRejectionTuning.SABRE_DETAIL_VARIANCE_RATIO_END} " + "alignmentInputGain=${referenceCalibration.alignmentGain} " + "alignmentDomain=signed-s16", ) diff --git a/app/src/main/java/com/hinnka/mycamera/processor/MgcSabreRejectionTuning.kt b/app/src/main/java/com/hinnka/mycamera/processor/MgcSabreRejectionTuning.kt index 28348cba..f2ee0788 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/MgcSabreRejectionTuning.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/MgcSabreRejectionTuning.kt @@ -1,6 +1,6 @@ package com.hinnka.mycamera.processor -/** MGC 9.7.047 V25 Sabre/Spatial rejection defaults and runtime resolution scaling. */ +/** MGC V25 rejection defaults, resolution scaling, and Photon Classic-Sabre detail tuning. */ internal object MgcSabreRejectionTuning { data class FlowVariationThresholds( val unblockerReduction: Float, @@ -12,6 +12,17 @@ internal object MgcSabreRejectionTuning { const val EXTRA_MOTION_ROBUSTNESS_BOOST = 6f const val MOTION_ROBUSTNESS_VARIANCE_THRESHOLD = 25f + /** + * Photon Classic-Sabre tuning, not shared with Spatial/YUV rejection. Keep V25's measured + * variance allowance near the noise floor, then tighten it only when BOTH guides contain + * structure well above BOTH noise estimates. The bicubic comparison and noise floor remain + * unchanged; this reduces admission of residual misalignment without restoring asymmetric + * guide filtering. Ratios refer to variance, not amplitude SNR. + */ + const val SABRE_DETAIL_VARIANCE_RATIO_START = 8f + const val SABRE_DETAIL_VARIANCE_RATIO_END = 32f + const val SABRE_DETAIL_VARIANCE_SCALE = 1.25f + private const val REFERENCE_GUIDE_WIDTH = 2016f private const val BASE_FLOW_VARIATION_THRESHOLD = 1e-4f /** diff --git a/docs/research/mgc-sabre-rejection-audit.md b/docs/research/mgc-sabre-rejection-audit.md index 2755bbe7..139eba78 100644 --- a/docs/research/mgc-sabre-rejection-audit.md +++ b/docs/research/mgc-sabre-rejection-audit.md @@ -1,5 +1,9 @@ # MGC V25 Sabre 区域误拒绝排查 +本文记录双侧 bicubic 修复时与 V25 的历史等价验证。后续仅对 Classic Sabre +增加了[结构区域拒绝调校](../mgc-sabre-detail-rejection.md),保留对称滤波;当前生产 +shader 的结构接纳权重有意偏离 V25,历史逐字节一致结论不覆盖这项调校。 + ## 结论 经典 Sabre 的基准帧 reference-color 预滤波 pass 缺失,且 alternate guide 使用了 @@ -64,6 +68,9 @@ R8 rejection MRT、R8 DilateMask 和回读。 ## 复跑 +以下原版等价流程应使用历史 1.28.0.1 源码/当时导出的 shader,并为验证脚本增加 +`--expect-v25`。当前生产 shader 已有结构调校,应按后续调校文档运行默认验证模式。 + 先按项目要求在沙箱外执行 Kotlin 编译,再从项目根目录运行以下 PowerShell。 基线提交固定为修复前的 `2cf1e3cb8963412343484c593deaf9d2665e5810`。 diff --git a/scripts/research/validate_mgc_sabre_rejection.py b/scripts/research/validate_mgc_sabre_rejection.py index 28a5d7a4..c0bc67f1 100644 --- a/scripts/research/validate_mgc_sabre_rejection.py +++ b/scripts/research/validate_mgc_sabre_rejection.py @@ -6,9 +6,12 @@ Run with uv outside the sandbox. --shader-dir contains the JVM-exported production base.frag, rejection.frag and dilate.frag, plus the pre-fix old-rejection.frag. This exercises desktop GL, not an Android device or its installed application. +The default checks detail-adaptive rejection; --expect-v25 checks historical parity. +Results describe rejection weights, not complete RAW fusion, image sharpness or MTF. """ from pathlib import Path +from dataclasses import dataclass import argparse import json import re @@ -28,12 +31,157 @@ void main() { """ +@dataclass +class Case: + name: str + guide: np.ndarray + alternate: np.ndarray + flow: tuple + family: str + fully_accepted: bool = False + low_detail: bool = False + residual_detail: bool = False + + +def synthetic_cases(width, height): + """The original 26 synthetic-guide cases, without camera sampling assumptions.""" + y, x = np.mgrid[:height, :width] + flat = np.full((height, width, 4), 0.5) + flat[:, :, 3] = 0.0005 * 1024 + stripes = flat.copy() + stripes[:, :, 1] = 0.25 + (x % 2) * 0.5 + stripes[:, :, 3] = -(0.5 ** 2 * 20 / 81) * 1024 + rgb = flat.copy() + rgb[:, :, :3] = (0.5 + 0.15 * np.sin(x * 0.5) * np.cos(y * 0.3))[:, :, None] + rgb[:, :, 3] = (0.001 + (x % 7) * 0.0001) * 1024 + mixed = rgb.copy() + mixed[:, :, 3] *= np.where((x + y) % 3 == 0, -1, 1) + changed = flat.copy() + changed[:, :, :3] = 0.8 + zero = (0, 0, 0, 0) + cases = [ + Case("identical_flat", flat, flat, zero, "synthetic", True, True), + Case("identical_green_stripes", stripes, stripes, zero, "synthetic", True), + Case("identical_rgb_texture", rgb, rgb, zero, "synthetic", True, True), + Case("mixed_variance_signs", mixed, mixed, zero, "synthetic", low_detail=True), + Case("aligned_integer_shift", stripes, np.roll(stripes, 1, axis=1), + (1 / width, 0, 0, 0), "synthetic", True), + Case("fractional_flow", rgb, rgb, (0.37 / width, -0.21 / height, 0, 0), + "synthetic", low_detail=True), + Case("changed_content", flat, changed, zero, "synthetic", low_detail=True), + ] + for green in (False, True): + for variance in (0.0005, 0.02): + edge = flat.copy() + edge[:, :, :3] = np.where(x[:, :, None] < width // 2, 0.25, 0.75) + edge[:, :, 3] = variance * 1024 * (-1 if green else 1) + for offset in (0.0, 0.25, 0.5, 1.0): + cases.append(Case( + f"edge_green{green}_variance{variance}_residual{offset}", + edge, edge, (offset / width, 0, 0, 0), "synthetic", + fully_accepted=offset == 0, + low_detail=variance == 0.0005, + residual_detail=variance == 0.02 and offset > 0, + )) + for offset in (0.25, 0.5, 1.0): + cases.append(Case(f"green_stripes_residual{offset}", stripes, stripes, + (offset / width, 0, 0, 0), "synthetic", residual_detail=True)) + return cases + + +def scene_guide(width, height, kind, shift, seed, sigma, blur=0.0): + """Sample a continuous scene and reproduce sqrt-domain guide statistics. + + The four synthetic Bayer channels share a continuous signal. Their independent + noise and the constant LUT are controlled test inputs, not a calibrated sensor. + Blur applies to the scene before sensor noise and guide statistics are added. + """ + y, x = np.mgrid[:height, :width] + px, py = x - shift[0], y - shift[1] + if kind == "flat": + signal = np.full_like(px, 0.5, dtype=float) + elif kind == "edge": + signal = 0.5 + 0.25 * np.tanh((px - width / 2 + 0.25 * (py - height / 2)) / 0.8) + else: + frequency = 0.2 if kind == "texture" else 0.4 + signal = 0.5 + 0.2 * np.sin(2 * np.pi * frequency * (px + 0.2 * py)) + if blur: + for axis in (0, 1): + padding = [(0, 0), (0, 0)] + padding[axis] = (1, 1) + padded = np.pad(signal, padding, mode="edge") + before = np.take(padded, np.arange(signal.shape[axis]), axis=axis) + after = np.take(padded, np.arange(signal.shape[axis]) + 2, axis=axis) + signal = signal * (1 - blur) + (before + after) * (blur / 2) + channels = signal[:, :, None] + np.random.default_rng(seed).normal( + 0, sigma, (height, width, 4) + ) + rgb_samples = channels[:, :, (0, 1, 3)].copy() + rgb_samples[:, :, 1] = (channels[:, :, 1] + channels[:, :, 2]) / 2 + rgb_pad = np.pad(rgb_samples, ((1, 1), (1, 1), (0, 0)), mode="edge") + green_pad = np.pad(channels[:, :, 1:3], ((1, 1), (1, 1), (0, 0)), mode="edge") + rgb_sum = np.zeros_like(rgb_samples) + rgb_sq = np.zeros_like(rgb_samples) + average = np.zeros_like(rgb_samples) + green_sum = np.zeros((height, width)) + green_sq = np.zeros((height, width)) + for j in range(3): + for i in range(3): + rgb = rgb_pad[j:j + height, i:i + width] + green = green_pad[j:j + height, i:i + width] + rgb_sum += rgb + rgb_sq += rgb * rgb + average += rgb * (0.5 if i == 1 else 0.25) * (0.5 if j == 1 else 0.25) + green_sum += green.sum(axis=2) + green_sq += (green * green).sum(axis=2) + rgb_var = np.maximum(0, rgb_sq / 9 - (rgb_sum / 9) ** 2) + green_var = np.maximum(0, green_sq / 18 - (green_sum / 18) ** 2) + green_only = green_var > 6 * 0.0005 + result = np.empty((height, width, 4)) + result[:, :, :3] = average + result[:, :, 1] = np.where(green_only, rgb_samples[:, :, 1], average[:, :, 1]) + result[:, :, 3] = 1024 * np.where( + green_only, -np.maximum(rgb_var[:, :, 1], green_var), rgb_var.mean(axis=2) + ) + return result + + +def sampled_cases(width, height): + """72 sampled-scene cases plus 12 independently blurred alternate frames.""" + cases = [] + for kind in ("flat", "edge", "texture", "fine_texture"): + for sigma in (0.0, 0.0316227766): + reference = scene_guide(width, height, kind, (0.0, 0.0), 123, sigma) + for shift in ((0.0, 0.0), (0.25, -0.25), (0.5, 0.25)): + alternate = scene_guide(width, height, kind, shift, 456, sigma) + for residual in (0.0, 0.25, 0.5): + cases.append(Case( + f"sampled_{kind}_sigma{sigma}_shift{shift}_residual{residual}", + reference, alternate, + ((shift[0] + residual) / width, shift[1] / height, 0, 0), + "sampled", + fully_accepted=sigma == 0 and shift == (0.0, 0.0) and residual == 0, + low_detail=kind == "flat", + residual_detail=kind != "flat" and residual > 0, + )) + if kind != "flat": + for blur in (0.15, 0.35): + alternate = scene_guide(width, height, kind, (0.0, 0.0), 456, sigma, blur) + cases.append(Case( + f"blurred_{kind}_sigma{sigma}_blur{blur}", reference, + alternate, (0, 0, 0, 0), "blurred", + )) + return cases + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--mgc-library", type=Path, required=True) parser.add_argument("--shader-dir", type=Path, required=True) parser.add_argument("--width", type=int, default=64) parser.add_argument("--height", type=int, default=64) + parser.add_argument("--expect-v25", action="store_true", help="Require historical V25 parity.") + parser.add_argument("--quiet", action="store_true", help="Print only the final summary.") args = parser.parse_args() data = args.mgc_library.read_bytes() chunks = {} @@ -135,7 +283,7 @@ def main(): base_tex = filtered sampler_names = ("base_frame_guide_texture", "alt_frame_guide_texture", "alt_flow_texture", "unblocker_texture", "noise_estimates_texture") if is_original else ("uBaseGuide", "uAltGuide", "uFlow", "uUnblocker", "uNoiseEstimates") outputs = draw( - {"original": "original_rejection", "fixed": "rejection", "old": "old-rejection"}[version], + {"original": "original_rejection", "production": "rejection", "old": "old-rejection"}[version], dict(zip(sampler_names, (base_tex, alt_tex, flow, unblocker, noise))), original_uniforms if is_original else production_uniforms, (width, height), (1, 1), "f1", @@ -145,54 +293,100 @@ def main(): resources.append(weight) reverse = np.frombuffer(outputs[0].read(), dtype=np.uint8).reshape(height, width).copy() accepted = np.frombuffer(weight.read(), dtype=np.uint8).reshape(height // 2, width // 2).copy() + pixel_difference = np.frombuffer(outputs[1].read(), dtype=np.uint8).reshape(height, width).copy() for item in resources: item.release() - return reverse, accepted + return reverse, accepted, pixel_difference - y, x = np.mgrid[:height, :width] - flat = np.full((height, width, 4), 0.5) - flat[:, :, 3] = 0.0005 * 1024 - stripes = flat.copy() - stripes[:, :, 1] = 0.25 + (x % 2) * 0.5 - stripes[:, :, 3] = -(0.5 ** 2 * 20 / 81) * 1024 - rgb = flat.copy() - rgb[:, :, :3] = (0.5 + 0.15 * np.sin(x * 0.5) * np.cos(y * 0.3))[:, :, None] - rgb[:, :, 3] = (0.001 + (x % 7) * 0.0001) * 1024 - mixed = rgb.copy() - mixed[:, :, 3] *= np.where((x + y) % 3 == 0, -1, 1) - changed = flat.copy() - changed[:, :, :3] = 0.8 - shifted = np.roll(stripes, 1, axis=1) - cases = ( - ("identical_flat", flat, flat, (0, 0, 0, 0)), - ("identical_green_stripes", stripes, stripes, (0, 0, 0, 0)), - ("identical_rgb_texture", rgb, rgb, (0, 0, 0, 0)), - ("mixed_variance_signs", mixed, mixed, (0, 0, 0, 0)), - ("aligned_integer_shift", stripes, shifted, (1 / width, 0, 0, 0)), - ("fractional_flow", rgb, rgb, (0.37 / width, -0.21 / height, 0, 0)), - ("changed_content", flat, changed, (0, 0, 0, 0)), - ) - report = {"renderer": ctx.info["GL_RENDERER"], "size": [width, height], "source_offsets": {name: offsets[name] for name in ("kBaseFrameRefColorEntryPoint", "kFunctionSampleBicubic", "kRejectionFunctions")}, "cases": []} - for name, guide, alt, flow in cases: - results = {version: run(guide, alt, flow, version) for version in ("original", "fixed", "old")} - record = {"name": name} - for version, (reverse, weight) in results.items(): + cases = synthetic_cases(width, height) + sampled_cases(width, height) + report = { + "renderer": ctx.info["GL_RENDERER"], "size": [width, height], + "mode": "historical_v25_parity" if args.expect_v25 else "detail_adaptive_rejection", + "versions": { + "original": "Embedded MGC V25 Classic Sabre with symmetric bicubic rejection", + "production": "JVM-exported application shaders supplied by --shader-dir", + "old": "Pre-fix asymmetric rejection supplied as old-rejection.frag", + }, + "scope": "Desktop GL rejection and final acceptance maps; no RAW merge, image MTF or device validation.", + "inputs": "26 synthetic-guide, 72 sampled-scene and 12 blurred-alternate cases; fixed noise LUT and zero motion prior/unblocker.", + "source_offsets": {name: offsets[name] for name in ( + "kBaseFrameRefColorEntryPoint", "kFunctionSampleBicubic", "kRejectionFunctions" + )}, + "cases": [], + } + reduced_synthetic_edges = 0 + reduced_synthetic_stripes = 0 + for case in cases: + results = { + version: run(case.guide, case.alternate, case.flow, version) + for version in ("original", "production", "old") + } + record = {"name": case.name, "family": case.family} + for version, (reverse, weight, pixel_difference) in results.items(): interior = weight[4:-4, 4:-4] - record[version] = {"mean_acceptance": float(interior.mean() / 255), "fully_rejected_fraction": float((interior == 0).mean())} - max_error = max(int(np.abs(a.astype(int) - b.astype(int)).max()) for a, b in zip(results["original"], results["fixed"])) - record["max_v25_error_u8"] = max_error - # Allow a single U8 quantization code for GPU arithmetic scheduling differences. - assert max_error <= 1, record - if name.startswith("identical") or name == "aligned_integer_shift": - assert record["fixed"]["mean_acceptance"] == 1.0, record - if name == "identical_green_stripes": + record[version] = { + "mean_acceptance": float(interior.mean() / 255), + "fully_rejected_fraction": float((interior == 0).mean()), + "edge_band_acceptance": float(weight[4:-4, width // 4 - 2:width // 4 + 2].mean() / 255), + "center_row": (weight[height // 4, width // 4 - 4:width // 4 + 4].astype(float) / 255).tolist(), + "mean_pixel_difference": float(pixel_difference[8:-8, 8:-8].mean() / 255), + } + original, production = results["original"], results["production"] + map_errors = { + label: int(np.abs(a.astype(int) - b.astype(int)).max()) + for label, a, b in zip(("reverse_rejection", "final_acceptance", "pixel_difference"), original, production) + } + record["max_difference_from_v25_u8"] = map_errors + acceptance_delta = production[1].astype(int) - original[1].astype(int) + record["max_acceptance_increase_u8"] = int(acceptance_delta.max()) + record["acceptance_reduced_fraction"] = float((acceptance_delta[4:-4, 4:-4] < 0).mean()) + record["low_detail_expected_unchanged"] = case.low_detail + if args.expect_v25: + # One U8 code permits equivalent arithmetic scheduling on another desktop GPU. + assert max(map_errors.values()) <= 1, record + else: + assert map_errors["pixel_difference"] == 0, record + assert record["max_acceptance_increase_u8"] <= 1, record + if case.low_detail: + assert max(map_errors.values()) == 0, record + if case.family == "synthetic" and case.residual_detail: + reduced = record["acceptance_reduced_fraction"] > 0 + if case.name.startswith("edge_"): + reduced_synthetic_edges += reduced + else: + reduced_synthetic_stripes += reduced + if case.fully_accepted: + assert record["production"]["mean_acceptance"] == 1.0, record + if case.name == "identical_green_stripes": assert record["old"]["fully_rejected_fraction"] == 1.0, record - if name == "changed_content": - assert record["fixed"]["fully_rejected_fraction"] == 1.0, record + if case.name == "changed_content": + assert record["production"]["fully_rejected_fraction"] == 1.0, record report["cases"].append(record) - print(json.dumps(record)) - (args.shader_dir / f"gpu-probe-results-{width}x{height}.json").write_text(json.dumps(report, indent=2) + "\n") - print("PASS: production shaders match V25; static texture rejection is removed and content rejection is retained.") + if not args.quiet: + print(json.dumps(record)) + if not args.expect_v25: + assert reduced_synthetic_edges > 0, "No residual synthetic edge became more selective." + assert reduced_synthetic_stripes > 0, "No residual synthetic stripe became more selective." + report["summary"] = { + "case_count": len(cases), + "family_counts": {family: sum(case.family == family for case in cases) + for family in ("synthetic", "sampled", "blurred")}, + "low_detail_unchanged_cases": sum(case.low_detail for case in cases), + "fully_accepted_cases": sum(case.fully_accepted for case in cases), + "reduced_synthetic_edges": reduced_synthetic_edges, + "reduced_synthetic_stripes": reduced_synthetic_stripes, + "passed": True, + } + output = args.shader_dir / f"gpu-probe-results-{width}x{height}.json" + output.write_text(json.dumps(report, indent=2) + "\n") + noise.release() + unblocker.release() + for program in programs.values(): + program.release() + ctx.release() + expectation = "historical V25 parity" if args.expect_v25 else "detail-adaptive rejection invariants" + print(f"PASS: {len(cases)} cases verify {expectation}. Report: {output}") + print("Scope: desktop GPU acceptance weights, not complete-fusion sharpness or MTF.") if __name__ == "__main__":