diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 793d9122..55a4bfe6 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -183,6 +183,114 @@ set_source_files_properties( OBJECT_DEPENDS "${MGC_GUIDED_CAPSULE}" ) +set( + MGC_RAISR_CAPSULE + "${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_raisr_capsule.bin" +) +set( + MGC_RAISR_CAPSULE_SHA256 + "d6c952ed507e340fb4e8075d7277126453d0faef35803d1add9a2e76e835f7cb" +) +if(NOT EXISTS "${MGC_RAISR_CAPSULE}") + message( + FATAL_ERROR + "MGC RAISR capsule is missing; regenerate it with " + "scripts/research/generate_mgc_raisr_static_asm.py" + ) +endif() +file(SHA256 "${MGC_RAISR_CAPSULE}" MGC_RAISR_CAPSULE_ACTUAL_SHA256) +if(NOT MGC_RAISR_CAPSULE_ACTUAL_SHA256 STREQUAL MGC_RAISR_CAPSULE_SHA256) + message( + FATAL_ERROR + "MGC RAISR capsule hash mismatch; regenerate it with " + "scripts/research/generate_mgc_raisr_static_asm.py" + ) +endif() +set( + MGC_RAISR_ASM + "${CMAKE_CURRENT_BINARY_DIR}/mgc_raisr_static.S" +) +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_raisr_static.S.in" + "${MGC_RAISR_ASM}" + @ONLY +) +set_source_files_properties( + "${MGC_RAISR_ASM}" + PROPERTIES + GENERATED TRUE + OBJECT_DEPENDS "${MGC_RAISR_CAPSULE}" +) + +set( + MGC_RAISR_FILTERS + "${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_raisr_filters.bin" +) +set( + MGC_RAISR_FILTERS_SHA256 + "0ace2b67b820732dd0cccebeea867521cf9144721196574918f618a1da9ed3c6" +) +set( + MGC_RAISR_RANDOMNESS_LUT + "${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_raisr_randomness_lut.bin" +) +set( + MGC_RAISR_RANDOMNESS_LUT_SHA256 + "dd3e825c6571e9371bc94c3b781b6b6a652eaeb3a1b20544a61e0f573519398b" +) +if(NOT EXISTS "${MGC_RAISR_FILTERS}") + message( + FATAL_ERROR + "MGC RAISR filter bank is missing; regenerate it with " + "scripts/research/extract_mgc_raisr_filters.py" + ) +endif() +file(SHA256 "${MGC_RAISR_FILTERS}" MGC_RAISR_FILTERS_ACTUAL_SHA256) +if(NOT MGC_RAISR_FILTERS_ACTUAL_SHA256 STREQUAL MGC_RAISR_FILTERS_SHA256) + message( + FATAL_ERROR + "MGC RAISR filter bank hash mismatch; regenerate it with " + "scripts/research/extract_mgc_raisr_filters.py" + ) +endif() +if(NOT EXISTS "${MGC_RAISR_RANDOMNESS_LUT}") + message( + FATAL_ERROR + "MGC RAISR randomness LUT is missing; regenerate it with " + "scripts/research/extract_mgc_raisr_randomness_lut.py" + ) +endif() +file( + SHA256 + "${MGC_RAISR_RANDOMNESS_LUT}" + MGC_RAISR_RANDOMNESS_LUT_ACTUAL_SHA256 +) +if( + NOT MGC_RAISR_RANDOMNESS_LUT_ACTUAL_SHA256 + STREQUAL MGC_RAISR_RANDOMNESS_LUT_SHA256 +) + message( + FATAL_ERROR + "MGC RAISR randomness LUT hash mismatch; regenerate it with " + "scripts/research/extract_mgc_raisr_randomness_lut.py" + ) +endif() +set( + MGC_RAISR_TABLES_ASM + "${CMAKE_CURRENT_BINARY_DIR}/mgc_raisr_tables_static.S" +) +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_raisr_tables_static.S.in" + "${MGC_RAISR_TABLES_ASM}" + @ONLY +) +set_source_files_properties( + "${MGC_RAISR_TABLES_ASM}" + PROPERTIES + GENERATED TRUE + OBJECT_DEPENDS "${MGC_RAISR_FILTERS};${MGC_RAISR_RANDOMNESS_LUT}" +) + set( MGC_SPATIAL_RGB_CAPSULE "${CMAKE_CURRENT_SOURCE_DIR}/mgc_denoise_static/mgc_spatial_rgb_merge_capsule.bin" @@ -230,6 +338,8 @@ set_property( "${MGC_DEMOIRE_ASM}" "${MGC_SABRE_ASM}" "${MGC_SPATIAL_RGB_ASM}" + "${MGC_RAISR_ASM}" + "${MGC_RAISR_TABLES_ASM}" ) # 4. 添加头文件路径 @@ -341,8 +451,12 @@ add_library(my-native-lib SHARED 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 + mgc_denoise_static/mgc_raisr_driver.cpp "${MGC_GUIDED_ASM}" "${MGC_SHARPEN_ASM}" + "${MGC_RAISR_ASM}" + "${MGC_RAISR_TABLES_ASM}" "${MGC_DENOISE_ASM}" "${MGC_DEMOIRE_ASM}" "${MGC_SABRE_ASM}" diff --git a/app/src/main/cpp/mgc_denoise_static/mgc_raisr_bands.h b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_bands.h new file mode 100644 index 00000000..3580561b --- /dev/null +++ b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_bands.h @@ -0,0 +1,109 @@ +// Horizontal-band runner for the lifted MGC V25 RAISR chain. +// +// The chain upscales in place, so a single call needs one buffer holding the +// input image and its 2x output: 64 bytes per source pixel, i.e. 800 MB for a +// 12 MP frame. This runner instead distributes the image into horizontal bands +// bounded by the requested core capacity, feeds each band kBandHaloPx rows beyond its +// own core, and hands every finished core row to a sink. The on-device probe +// measured the haloed crop as bit-identical to the full-frame result from two +// rows of halo on (docs/research/mgc-raisr-output-upscale.md), so banding only +// changes the peak allocation. +// +// `Source` must provide `void Fill(int top, int rows, float* destination)`, +// filling `rows` rows of `width` RGBA float pixels each; `Sink` must provide +// `void Write(int row, const float* pixels, int count)`, storing `count` RGBA +// float pixels at the given row of the 2x core. + +#ifndef PHOTON_MGC_RAISR_BANDS_H +#define PHOTON_MGC_RAISR_BANDS_H + +#include +#include +#include +#include + +namespace photon_raisr { + +// Rows of context a band needs beyond its own core. +constexpr int kBandHaloPx = 4; + +// Floor for the requested band capacity. Distribute the core evenly across +// bands so a short remainder cannot produce an undersized AOT input. When more +// than one band is needed, each core has at least eight rows at this floor. +// A one-to-three-row tail with only the top halo would fail composite's +// image_fallback_ extent check even when all preceding bands were large enough. +constexpr int kMinimumBandCoreRows = 16; + +// Peak scratch one band may occupy. +constexpr int64_t kBandScratchBudgetBytes = 32 * 1024 * 1024; + +// Bytes one source pixel occupies across the band buffer: the chain reads RGBA +// float (16) and writes the 2x RGBA float image (64). +constexpr int64_t kBandBytesPerSourcePixel = 64; + +inline uint8_t ToU8(float value) { + const float scaled = value * 255.0f + 0.5f; + if (!(scaled > 0.0f)) { + return 0; + } + return scaled >= 255.0f ? 255 : uint8_t(scaled); +} + +extern "C" int photon_mgc_raisr_upscale_rgba(const float* input, int width, int height, + float* output); + +// Core rows one band may cover at this width without leaving the budget, never +// fewer than kMinimumBandCoreRows. At any real frame width the budget is the +// binding constraint; the floor only takes over past ~21k columns, where it +// still caps a band at width * 1536 bytes. +inline int BandCoreRows(int width) { + const int64_t rows = kBandScratchBudgetBytes / (int64_t(width) * kBandBytesPerSourcePixel); + return int(std::max(kMinimumBandCoreRows, rows - 2 * kBandHaloPx)); +} + +template +int RunBands(const Source& source, const Sink& sink, int width, int height, int core_left, + int core_top, int core_width, int core_height, int band_core_rows) { + if (width <= 0 || height <= 0 || core_width <= 0 || core_height <= 0 || core_left < 0 || + core_top < 0 || core_left + core_width > width || core_top + core_height > height) { + return -1; + } + const int rows_per_band = std::min(std::max(kMinimumBandCoreRows, band_core_rows), height); + const int band_count = 1 + (core_height - 1) / rows_per_band; + const int base_rows = core_height / band_count; + const int extra_rows = core_height % band_count; + const int out_width = width * 2; + std::vector band; + try { + band.resize(size_t(width) * size_t(rows_per_band + 2 * kBandHaloPx) * 16); + } catch (const std::bad_alloc&) { + return -2; + } + int top = core_top; + for (int index = 0; index < band_count; ++index) { + const int rows = base_rows + (index < extra_rows ? 1 : 0); + const int band_top = std::max(0, top - kBandHaloPx); + const int band_bottom = std::min(height, top + rows + kBandHaloPx); + const int band_height = band_bottom - band_top; + source.Fill(band_top, band_height, band.data()); + // The chain builds all of its UInt8 planes from the input before it + // writes the first output pixel, so one buffer can carry both. + const int status = + photon_mgc_raisr_upscale_rgba(band.data(), width, band_height, band.data()); + if (status != 0) { + return status; + } + for (int row = 0; row < rows * 2; ++row) { + const float* line = + band.data() + + (size_t(row + (top - band_top) * 2) * out_width + size_t(core_left) * 2) * 4; + sink.Write((top - core_top) * 2 + row, line, core_width * 2); + } + top += rows; + } + return 0; +} + +} // namespace photon_raisr + +#endif // PHOTON_MGC_RAISR_BANDS_H diff --git a/app/src/main/cpp/mgc_denoise_static/mgc_raisr_capsule.bin b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_capsule.bin new file mode 100644 index 00000000..7bbff883 Binary files /dev/null and b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_capsule.bin differ diff --git a/app/src/main/cpp/mgc_denoise_static/mgc_raisr_driver.cpp b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_driver.cpp new file mode 100644 index 00000000..ce8c34ec --- /dev/null +++ b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_driver.cpp @@ -0,0 +1,402 @@ +// MGC V25 RAISR output magnification driver. +// +// Chains the five lifted AOT kernels into the finish-stage 2x upscale that the +// original performs in `RaisrUpsample`. The lift itself is byte-identical to the +// pinned libgcastartup.so; this file only rebuilds the npcam glue around it. +// +// Buffer contract, measured on device against the lifted kernels (see +// docs/research/mgc-raisr-output-upscale.md): the whole chain runs in the UInt8 +// finish domain, only the filter bank is int16. Layouts differ per kernel: +// rgbx_in_ UInt8, 3 channels, interleaved (x stride 3, channel stride 1) +// orientation in/out, composite in/out: UInt8, 1 or 3 channels, planar +// randomness_lut: UInt8, one dimension of 256 +// +// Two sub-steps of the original are not part of the lifted kernels and are +// rebuilt here from their documented behaviour: +// * the cheap upscale that produces the composite's fallback luma. The +// original runs it inside npcam C++ that was not lifted, so this uses plain +// bilinear interpolation on the same luma grid. +// * the chroma recombination, which lives in the original's caller +// (libgcastartup.so+0x3364BC8) and has not been reconstructed. Chroma is +// carried through bilinearly and recombined with the BT.601 full-range +// matrix - the same matrix RgbToGray3ChOptHalideU8 uses, which the device +// probe confirmed numerically (grey(0,64,32) == 41 == 0.299*0 + 0.587*64 + +// 0.114*32). + +#include +#include +#include +#include +#include + +#include "mgc_raisr_bands.h" + +namespace { + +constexpr const char* kTag = "PLog_MgcRaisr"; + +// The band buffer is quantised exactly like the driver quantises its own input, +// so the 8-bit round trip through the float band buffer is lossless. +using photon_raisr::ToU8; + +struct HalideType { + uint8_t code; + uint8_t bits; + uint16_t lanes; +}; + +struct HalideDimension { + int32_t min; + int32_t extent; + int32_t stride; + uint32_t flags; +}; + +struct HalideBuffer { + uint64_t device; + const void* device_interface; + uint8_t* host; + uint64_t flags; + HalideType type; + int32_t dimensions; + const HalideDimension* dim; + void* padding; +}; + +static_assert(sizeof(HalideType) == 4, "HalideType layout"); +static_assert(sizeof(HalideDimension) == 16, "HalideDimension layout"); +static_assert(sizeof(HalideBuffer) == 56, "HalideBuffer layout"); + +// V25 compiled-params defaults that have a consumer in the lifted code. The +// stored f32 pairs at +0x18/+0x1C are stale in the binary and must not be +// copied; the self-consistent category triple is (24 angles, 3 coherence, +// 3 strength) with a 5x5 kernel over 4 shifts, i.e. 216 classes and 43200 bytes +// of filter data. +constexpr int32_t kNumAngleBuckets = 24; +constexpr float kMinStrength = 0.0523100868f; +constexpr float kMaxStrength = 0.00511798495f; +constexpr float kMinCoherence = -0.0055033979f; +constexpr float kMaxCoherence = -0.0482351705f; +// Composite strength parameters, the fixed-point forms of the constants the +// original caller feeds (0x6BE0390 through fcvtzs #8/#8/#4/#8). +constexpr int32_t kFallbackStrengthQ8 = 0; +constexpr int32_t kArtifactCorrectionMaxStrengthQ8 = 3; +constexpr int32_t kArtifactMapScaleQ4 = 0; +constexpr int16_t kArtifactMapBiasQ8 = 1; +constexpr int16_t kDebugOutputSelect = 0; + +HalideBuffer MakeBuffer(void* host, uint8_t code, uint8_t bits, int32_t dimensions, + const HalideDimension* dim, uint16_t lanes = 1) { + HalideBuffer buffer{}; + buffer.host = static_cast(host); + buffer.type = HalideType{code, bits, lanes}; + buffer.dimensions = dimensions; + buffer.dim = dim; + return buffer; +} + +HalideBuffer MakeU8Buffer(void* host, int32_t dimensions, const HalideDimension* dim) { + return MakeBuffer(host, 1, 8, dimensions, dim); +} + +float Clamp01(float value) { return value < 0.0f ? 0.0f : (value > 1.0f ? 1.0f : value); } + +// Bilinear 2x sample of a single channel grid. Output pixel X maps to source +// coordinate X/2 - 0.25, matching the half-pixel convention the per-shift +// kernel's phase grid implies. +uint8_t SampleBilinear2x(const std::vector& source, int width, int height, + int out_x, int out_y) { + const float source_x = 0.5f * out_x - 0.25f; + const float source_y = 0.5f * out_y - 0.25f; + int x0 = int(std::floor(source_x)); + int y0 = int(std::floor(source_y)); + const float fx = source_x - float(x0); + const float fy = source_y - float(y0); + int x1 = x0 + 1; + int y1 = y0 + 1; + if (x0 < 0) x0 = 0; + if (y0 < 0) y0 = 0; + if (x1 < 0) x1 = 0; + if (y1 < 0) y1 = 0; + if (x0 > width - 1) x0 = width - 1; + if (x1 > width - 1) x1 = width - 1; + if (y0 > height - 1) y0 = height - 1; + if (y1 > height - 1) y1 = height - 1; + const float top = float(source[size_t(y0) * width + x0]) * (1.0f - fx) + + float(source[size_t(y0) * width + x1]) * fx; + const float bottom = float(source[size_t(y1) * width + x0]) * (1.0f - fx) + + float(source[size_t(y1) * width + x1]) * fx; + const float value = top * (1.0f - fy) + bottom * fy + 0.5f; + return value <= 0.0f ? 0 : (value >= 255.0f ? 255 : uint8_t(value)); +} + +// sRGB-encoded BT.601 full range, the matrix RgbToGray3ChOptHalideU8 was measured +// to use. Chroma quantisation saturates before narrowing: rounding a positive +// full-scale colour difference can produce 256, outside the UInt8 domain. +void RgbToChroma(uint8_t r, uint8_t g, uint8_t b, uint8_t& cb, uint8_t& cr) { + cb = uint8_t(std::clamp(((-43 * r - 85 * g + 128 * b + 128) >> 8) + 128, 0, 255)); + cr = uint8_t(std::clamp(((128 * r - 107 * g - 21 * b + 128) >> 8) + 128, 0, 255)); +} + +void YcbcrToRgb(int y, int cb, int cr, float& r, float& g, float& b) { + const int c = cb - 128; + const int d = cr - 128; + const int red = y + ((91881 * d) >> 16); + const int green = y - ((22554 * c + 46802 * d) >> 16); + const int blue = y + ((116130 * c) >> 16); + r = Clamp01(float(red < 0 ? 0 : (red > 255 ? 255 : red)) / 255.0f); + g = Clamp01(float(green < 0 ? 0 : (green > 255 ? 255 : green)) / 255.0f); + b = Clamp01(float(blue < 0 ? 0 : (blue > 255 ? 255 : blue)) / 255.0f); +} + +} // namespace + +extern "C" { +int photon_mgc_raisr_rgb_to_gray(void*, HalideBuffer*, HalideBuffer*); +int photon_mgc_raisr_orientation(void*, HalideBuffer*, int32_t, HalideBuffer*); +int photon_mgc_raisr_hash(void*, HalideBuffer*, int32_t, float, float, float, float, + HalideBuffer*); +int photon_mgc_raisr_upscale_2x(void*, HalideBuffer*, HalideBuffer*, HalideBuffer*, + HalideBuffer*); +int photon_mgc_raisr_composite(void*, HalideBuffer*, HalideBuffer*, HalideBuffer*, + HalideBuffer*, int32_t, int32_t, int32_t, int16_t, int16_t, + HalideBuffer*); +extern const int16_t photon_mgc_raisr_filters[]; +extern const uint8_t photon_mgc_raisr_randomness_lut[]; +} + + +// Runs the whole RAISR luma chain on one image. `input` is float RGBA in 0..1 +// sRGB, `output` must hold 2x the pixels in the same layout. Exposed with C +// linkage so the on-device probe can drive it without the app. +extern "C" int photon_mgc_raisr_upscale_rgba(const float* input, int width, int height, + float* output) try { + const int out_width = width * 2; + const int out_height = height * 2; + const size_t source_pixels = size_t(width) * height; + + // 1. rgbx_in_: UInt8, 3 channels, interleaved. + std::vector rgbx(source_pixels * 3); + for (size_t index = 0; index < source_pixels; ++index) { + rgbx[index * 3 + 0] = ToU8(input[index * 4 + 0]); + rgbx[index * 3 + 1] = ToU8(input[index * 4 + 1]); + rgbx[index * 3 + 2] = ToU8(input[index * 4 + 2]); + } + // 2. Luma. + std::vector gray(source_pixels); + // 3. Orientation input: the same luma as a planar 3 channel image. + std::vector gray3(source_pixels * 3); + // 4. Orientation output. + std::vector orientation(source_pixels * 3); + // 5. Filter class image, at the upscaled grid. + std::vector hash(size_t(out_width) * out_height); + // 6. RAISR luma at the upscaled grid. + std::vector raisr(size_t(out_width) * out_height); + // 7. Cheap fallback luma at the upscaled grid. + std::vector fallback(size_t(out_width) * out_height); + // 8. Composite output luma. + std::vector luma(size_t(out_width) * out_height); + + { + // rgbx_in_ is declared as three dimensions whose innermost stride is the + // channel count and whose channel dimension has stride 1, i.e. interleaved + // RGB. The on-device probe rejects a flattened two-dimensional form. + const HalideDimension dims[] = { + {0, width, 3, 0}, + {0, height, width * 3, 0}, + {0, 3, 1, 0}, + }; + HalideBuffer in = MakeU8Buffer(rgbx.data(), 3, dims); + const HalideDimension out_dims[] = { + {0, width, 1, 0}, + {0, height, width, 0}, + }; + HalideBuffer out = MakeU8Buffer(gray.data(), 2, out_dims); + const int result = photon_mgc_raisr_rgb_to_gray(nullptr, &in, &out); + if (result != 0) { + __android_log_print(ANDROID_LOG_ERROR, kTag, "rgb_to_gray failed: %d", result); + return result; + } + } + + for (size_t index = 0; index < source_pixels; ++index) { + for (int channel = 0; channel < 3; ++channel) { + gray3[size_t(channel) * source_pixels + index] = gray[index]; + } + } + { + const HalideDimension dims[] = { + {0, width, 1, 0}, + {0, height, width, 0}, + {0, 3, width * height, 0}, + }; + HalideBuffer in = MakeU8Buffer(gray3.data(), 3, dims); + HalideBuffer out = MakeU8Buffer(orientation.data(), 3, dims); + const int result = + photon_mgc_raisr_orientation(nullptr, &in, kNumAngleBuckets, &out); + if (result != 0) { + __android_log_print(ANDROID_LOG_ERROR, kTag, "orientation failed: %d", result); + return result; + } + } + { + const HalideDimension in_dims[] = { + {0, width, 1, 0}, + {0, height, width, 0}, + {0, 3, width * height, 0}, + }; + const HalideDimension out_dims[] = { + {0, out_width, 1, 0}, + {0, out_height, out_width, 0}, + }; + HalideBuffer in = MakeU8Buffer(orientation.data(), 3, in_dims); + HalideBuffer out = MakeU8Buffer(hash.data(), 2, out_dims); + const int result = photon_mgc_raisr_hash(nullptr, &in, kNumAngleBuckets, kMinStrength, + kMaxStrength, kMinCoherence, kMaxCoherence, + &out); + if (result != 0) { + __android_log_print(ANDROID_LOG_ERROR, kTag, "hash failed: %d", result); + return result; + } + } + + for (int y = 0; y < out_height; ++y) { + for (int x = 0; x < out_width; ++x) { + fallback[size_t(y) * out_width + x] = SampleBilinear2x(gray, width, height, x, y); + } + } + { + const HalideDimension luma_dims[] = { + {0, width, 1, 0}, + {0, height, width, 0}, + }; + const HalideDimension filter_dims[] = { + {0, 5, 1, 0}, + {0, 5, 5, 0}, + {0, 216, 25, 0}, + {0, 4, 5400, 0}, + }; + const HalideDimension up_dims[] = { + {0, out_width, 1, 0}, + {0, out_height, out_width, 0}, + }; + // The lifted filter bank is const; the AOT entry only reads it. + HalideBuffer in = MakeU8Buffer(gray.data(), 2, luma_dims); + HalideBuffer filters = MakeBuffer(const_cast(photon_mgc_raisr_filters), 0, 16, + 4, filter_dims); + HalideBuffer hash_buffer = MakeU8Buffer(hash.data(), 2, up_dims); + HalideBuffer out = MakeU8Buffer(raisr.data(), 2, up_dims); + const int result = + photon_mgc_raisr_upscale_2x(nullptr, &in, &filters, &hash_buffer, &out); + if (result != 0) { + __android_log_print(ANDROID_LOG_ERROR, kTag, "upscale_2x failed: %d", result); + return result; + } + } + { + const HalideDimension up_dims[] = { + {0, out_width, 1, 0}, + {0, out_height, out_width, 0}, + }; + const HalideDimension lut_dims[] = { + {0, 256, 1, 0}, + }; + HalideBuffer fallback_buffer = MakeU8Buffer(fallback.data(), 2, up_dims); + HalideBuffer raisr_buffer = MakeU8Buffer(raisr.data(), 2, up_dims); + HalideBuffer lut = MakeU8Buffer(const_cast(photon_mgc_raisr_randomness_lut), 1, + lut_dims); + HalideBuffer out = MakeU8Buffer(luma.data(), 2, up_dims); + // The artifact argument is present in the ABI but never read by the + // kernel; the original also passes the target buffer there. + const int result = photon_mgc_raisr_composite( + nullptr, &fallback_buffer, &raisr_buffer, &fallback_buffer, &lut, + kFallbackStrengthQ8, kArtifactCorrectionMaxStrengthQ8, kArtifactMapScaleQ4, + kArtifactMapBiasQ8, kDebugOutputSelect, &out); + if (result != 0) { + __android_log_print(ANDROID_LOG_ERROR, kTag, "composite failed: %d", result); + return result; + } + } + + // Chroma is carried through bilinearly and recombined with the RAISR luma. + std::vector cb(source_pixels); + std::vector cr(source_pixels); + for (size_t index = 0; index < source_pixels; ++index) { + RgbToChroma(rgbx[index * 3 + 0], rgbx[index * 3 + 1], rgbx[index * 3 + 2], + cb[index], cr[index]); + } + for (int y = 0; y < out_height; ++y) { + for (int x = 0; x < out_width; ++x) { + const int luma_value = luma[size_t(y) * out_width + x]; + const int cb_value = SampleBilinear2x(cb, width, height, x, y); + const int cr_value = SampleBilinear2x(cr, width, height, x, y); + float red = 0.0f; + float green = 0.0f; + float blue = 0.0f; + YcbcrToRgb(luma_value, cb_value, cr_value, red, green, blue); + float* pixel = output + (size_t(y) * out_width + x) * 4; + pixel[0] = red; + pixel[1] = green; + pixel[2] = blue; + pixel[3] = 1.0f; + } + } + return 0; +} catch (const std::bad_alloc&) { + // Every intermediate plane belongs to this call; unwind them before the + // failure crosses the C/JNI boundary and let the caller discard the output. + __android_log_print(ANDROID_LOG_ERROR, kTag, "unable to allocate RAISR intermediate planes"); + return -2; +} + + +namespace { + +// Whole 1x float RGBA image as a band source: the shape both the probe and any +// caller that already holds the frame uses. +class FullImageSource { +public: + FullImageSource(const float* pixels, int width) : pixels_(pixels), width_(width) {} + + void Fill(int top, int rows, float* destination) const { + std::memcpy(destination, pixels_ + size_t(top) * width_ * 4, + size_t(rows) * width_ * 4 * sizeof(float)); + } + +private: + const float* pixels_; + int width_; +}; + +// Whole 2x float RGBA image as a band sink. +class FullImageSink { +public: + FullImageSink(float* pixels, int out_width) : pixels_(pixels), out_width_(out_width) {} + + void Write(int row, const float* pixels, int count) const { + std::memcpy(pixels_ + size_t(row) * out_width_ * 4, pixels, + size_t(count) * 4 * sizeof(float)); + } + +private: + float* pixels_; + int out_width_; +}; + +} // namespace + +// The same chain, band by band, so a caller never needs the 64 bytes per source +// pixel one in-place call needs. `output` holds the 2x float RGBA image. +// +// `band_core_rows` is explicit so the probe can compare this against +// photon_mgc_raisr_upscale_rgba bit for bit at several band heights; the app +// passes photon_raisr::BandCoreRows(width), which keeps one band inside the +// scratch budget. +extern "C" int photon_mgc_raisr_upscale_rgba_banded(const float* input, int width, int height, + float* output, int band_core_rows) { + if (input == nullptr || output == nullptr) { + return -1; + } + return photon_raisr::RunBands(FullImageSource(input, width), FullImageSink(output, width * 2), + width, height, 0, 0, width, height, band_core_rows); +} diff --git a/app/src/main/cpp/mgc_denoise_static/mgc_raisr_filters.bin b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_filters.bin new file mode 100644 index 00000000..58002391 Binary files /dev/null and b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_filters.bin differ diff --git a/app/src/main/cpp/mgc_denoise_static/mgc_raisr_jni.cpp b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_jni.cpp new file mode 100644 index 00000000..3a269ba2 --- /dev/null +++ b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_jni.cpp @@ -0,0 +1,285 @@ +// JNI bridge that runs the lifted MGC V25 RAISR chain +// (mgc_raisr_driver.cpp) over Photon's own containers. +// +// The recovered ABI of the five lifted AOT kernels lives in +// docs/research/mgc-raisr-output-upscale.md. Nothing about the chain itself +// belongs in Kotlin: the band loop, its scratch budget, the half-float and +// ARGB_8888 to float conversion and the float to ARGB_8888 conversion all run +// here, so a Kotlin caller only hands over the frame it already holds and gets +// the finished 2x bitmap back. + +#include +#include + +#include +#include +#include +#include + +#include "mgc_raisr_bands.h" + +namespace { + +constexpr const char* kTag = "PLog_MgcRaisr"; + +// One Android bitmap locked for the duration of a single upscale. +class LockedBitmap { +public: + LockedBitmap() = default; + LockedBitmap(const LockedBitmap&) = delete; + LockedBitmap& operator=(const LockedBitmap&) = delete; + + ~LockedBitmap() { Unlock(); } + + bool Lock(JNIEnv* env, jobject bitmap) { + if (bitmap == nullptr) { + return false; + } + AndroidBitmapInfo info{}; + if (AndroidBitmap_getInfo(env, bitmap, &info) != ANDROID_BITMAP_RESULT_SUCCESS) { + return false; + } + void* pixels = nullptr; + if (AndroidBitmap_lockPixels(env, bitmap, &pixels) != ANDROID_BITMAP_RESULT_SUCCESS) { + return false; + } + env_ = env; + bitmap_ = bitmap; + info_ = info; + pixels_ = pixels; + return true; + } + + void Unlock() { + if (bitmap_ != nullptr) { + AndroidBitmap_unlockPixels(env_, bitmap_); + bitmap_ = nullptr; + pixels_ = nullptr; + } + } + + const uint8_t* bytes() const { return static_cast(pixels_); } + uint8_t* mutable_bytes() const { return static_cast(pixels_); } + int width() const { return int(info_.width); } + int height() const { return int(info_.height); } + size_t stride() const { return size_t(info_.stride); } + int32_t format() const { return info_.format; } + +private: + JNIEnv* env_ = nullptr; + jobject bitmap_ = nullptr; + AndroidBitmapInfo info_{}; + void* pixels_ = nullptr; +}; + +// IEEE binary16 to binary32, subnormals included: the finalized frame comes back +// from the GPU as an RGBA_F16 bitmap while the chain's input is RGBA float. +float HalfToFloat(uint16_t half) { + const uint32_t sign = uint32_t(half & 0x8000u) << 16; + const uint32_t exponent = (half >> 10) & 0x1Fu; + const uint32_t mantissa = half & 0x3FFu; + uint32_t bits = 0; + if (exponent == 0) { + if (mantissa != 0) { + uint32_t value = mantissa; + int shift = 0; + while ((value & 0x400u) == 0) { + value <<= 1; + ++shift; + } + bits = sign | (uint32_t(113 - shift) << 23) | ((value & 0x3FFu) << 13); + } else { + bits = sign; + } + } else if (exponent == 0x1Fu) { + bits = sign | 0x7F800000u | (mantissa << 13); + } else { + bits = sign | ((exponent + 112u) << 23) | (mantissa << 13); + } + float result = 0.0f; + std::memcpy(&result, &bits, sizeof(result)); + return result; +} + +// A finalized frame as a band source. RGBA_F16 carries the GPU readback in the +// working colour space, ARGB_8888 the same values already quantised; both map to +// the RGBA float the chain consumes, with the alpha the chain ignores set opaque. +class BitmapSource { +public: + BitmapSource(const uint8_t* pixels, size_t stride, int width, int32_t format) + : pixels_(pixels), + stride_(stride), + width_(width), + half_(format == ANDROID_BITMAP_FORMAT_RGBA_F16) {} + + void Fill(int top, int rows, float* destination) const { + for (int row = 0; row < rows; ++row) { + const uint8_t* source = pixels_ + size_t(top + row) * stride_; + float* target = destination + size_t(row) * width_ * 4; + for (int column = 0; column < width_; ++column) { + if (half_) { + uint16_t halves[4] = {}; + std::memcpy(halves, source + size_t(column) * 8, sizeof(halves)); + target[column * 4 + 0] = HalfToFloat(halves[0]); + target[column * 4 + 1] = HalfToFloat(halves[1]); + target[column * 4 + 2] = HalfToFloat(halves[2]); + } else { + const uint8_t* pixel = source + size_t(column) * 4; + target[column * 4 + 0] = pixel[0] / 255.0f; + target[column * 4 + 1] = pixel[1] / 255.0f; + target[column * 4 + 2] = pixel[2] / 255.0f; + } + target[column * 4 + 3] = 1.0f; + } + } + } + +private: + const uint8_t* pixels_; + size_t stride_; + int width_; + bool half_; +}; + +// The tiled path's texture readback: one float RGBA working tile, of which the +// core plus halo is the band region. +class TileSource { +public: + TileSource(const float* pixels, int tile_width, int region_width, int left, int top) + : pixels_(pixels), tile_width_(tile_width), region_width_(region_width), + left_(left), top_(top) {} + + void Fill(int top, int rows, float* destination) const { + for (int row = 0; row < rows; ++row) { + const float* source = pixels_ + (size_t(top_ + top + row) * tile_width_ + left_) * 4; + std::memcpy(destination + size_t(row) * region_width_ * 4, source, + size_t(region_width_) * 4 * sizeof(float)); + } + } + +private: + const float* pixels_; + int tile_width_; + int region_width_; + int left_; + int top_; +}; + +// The destination bitmap's pixels. Android's RGBA_8888 layout stores R, G, B and +// A in that byte order, and the alpha is opaque, so writing it directly keeps +// the bitmap out of the premultiplied-alpha path. +class ArgbSink { +public: + ArgbSink(uint8_t* pixels, size_t stride) : pixels_(pixels), stride_(stride) {} + + void Write(int row, const float* pixels, int count) const { + uint8_t* target = pixels_ + size_t(row) * stride_; + for (int column = 0; column < count; ++column) { + const float* pixel = pixels + size_t(column) * 4; + target[column * 4 + 0] = photon_raisr::ToU8(pixel[0]); + target[column * 4 + 1] = photon_raisr::ToU8(pixel[1]); + target[column * 4 + 2] = photon_raisr::ToU8(pixel[2]); + target[column * 4 + 3] = 0xFF; + } + } + +private: + uint8_t* pixels_; + size_t stride_; +}; + +bool IsSourceFormat(int32_t format) { + return format == ANDROID_BITMAP_FORMAT_RGBA_F16 || format == ANDROID_BITMAP_FORMAT_RGBA_8888; +} + +} // namespace + +// Upscales a whole finalized frame: `source` is the frame on its native grid and +// `destination` the empty 2x bitmap of RGBA_8888 pixels to fill. +extern "C" JNIEXPORT jint JNICALL +Java_com_hinnka_mycamera_raw_MgcRaisrUpscale_nativeUpscaleBitmap(JNIEnv* env, jclass, + jobject source, + jobject destination) { + LockedBitmap source_bitmap; + LockedBitmap destination_bitmap; + if (!source_bitmap.Lock(env, source) || !destination_bitmap.Lock(env, destination)) { + __android_log_print(ANDROID_LOG_ERROR, kTag, "unable to lock the frame bitmaps"); + return -1; + } + if (!IsSourceFormat(source_bitmap.format())) { + __android_log_print(ANDROID_LOG_ERROR, kTag, "unsupported source format: %d", + source_bitmap.format()); + return -1; + } + const int width = source_bitmap.width(); + const int height = source_bitmap.height(); + if (destination_bitmap.format() != ANDROID_BITMAP_FORMAT_RGBA_8888 || + destination_bitmap.width() != width * 2 || destination_bitmap.height() != height * 2) { + __android_log_print(ANDROID_LOG_ERROR, kTag, + "destination %dx%d format=%d does not match %dx%d", + destination_bitmap.width(), destination_bitmap.height(), + destination_bitmap.format(), width * 2, height * 2); + return -1; + } + const int status = photon_raisr::RunBands( + BitmapSource(source_bitmap.bytes(), source_bitmap.stride(), width, source_bitmap.format()), + ArgbSink(destination_bitmap.mutable_bytes(), destination_bitmap.stride()), width, height, 0, + 0, width, height, photon_raisr::BandCoreRows(width)); + if (status != 0) { + __android_log_print(ANDROID_LOG_ERROR, kTag, "banded upscale failed: %d", status); + } + return status; +} + +// Upscales one tile of a tiled render. `source` is the float RGBA readback of the +// whole working tile, which is larger than the core on every side, so the chain +// is fed the core plus photon_raisr::kBandHaloPx and the margin is cropped from +// the 2x result again. `destination` holds the core's 2x pixels. +extern "C" JNIEXPORT jint JNICALL +Java_com_hinnka_mycamera_raw_MgcRaisrUpscale_nativeUpscaleTile( + JNIEnv* env, jclass, jobject source, jint tile_width, jint tile_height, jint core_left, + jint core_top, jint core_width, jint core_height, jobject destination) { + if (source == nullptr || tile_width <= 0 || tile_height <= 0 || core_width <= 0 || + core_height <= 0 || core_left < 0 || core_top < 0 || core_left + core_width > tile_width || + core_top + core_height > tile_height) { + return -1; + } + auto* pixels = static_cast(env->GetDirectBufferAddress(source)); + if (pixels == nullptr) { + return -1; + } + const jlong capacity = env->GetDirectBufferCapacity(source); + if (capacity < jlong(tile_width) * tile_height * 4 * jlong(sizeof(float))) { + return -1; + } + const int left = std::max(0, core_left - photon_raisr::kBandHaloPx); + const int top = std::max(0, core_top - photon_raisr::kBandHaloPx); + const int right = std::min(tile_width, core_left + core_width + photon_raisr::kBandHaloPx); + const int bottom = + std::min(tile_height, core_top + core_height + photon_raisr::kBandHaloPx); + const int region_width = right - left; + const int region_height = bottom - top; + LockedBitmap destination_bitmap; + if (!destination_bitmap.Lock(env, destination)) { + __android_log_print(ANDROID_LOG_ERROR, kTag, "unable to lock the destination bitmap"); + return -1; + } + if (destination_bitmap.format() != ANDROID_BITMAP_FORMAT_RGBA_8888 || + destination_bitmap.width() != core_width * 2 || + destination_bitmap.height() != core_height * 2) { + __android_log_print(ANDROID_LOG_ERROR, kTag, + "tile destination %dx%d format=%d does not match %dx%d", + destination_bitmap.width(), destination_bitmap.height(), + destination_bitmap.format(), core_width * 2, core_height * 2); + return -1; + } + const int status = photon_raisr::RunBands( + TileSource(pixels, tile_width, region_width, left, top), + ArgbSink(destination_bitmap.mutable_bytes(), destination_bitmap.stride()), region_width, + region_height, core_left - left, core_top - top, core_width, core_height, + photon_raisr::BandCoreRows(region_width)); + if (status != 0) { + __android_log_print(ANDROID_LOG_ERROR, kTag, "banded tile upscale failed: %d", status); + } + return status; +} diff --git a/app/src/main/cpp/mgc_denoise_static/mgc_raisr_randomness_lut.bin b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_randomness_lut.bin new file mode 100644 index 00000000..ab548eb5 Binary files /dev/null and b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_randomness_lut.bin differ diff --git a/app/src/main/cpp/mgc_denoise_static/mgc_raisr_static.S.in b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_static.S.in new file mode 100644 index 00000000..9627225c --- /dev/null +++ b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_static.S.in @@ -0,0 +1,1329 @@ +/* Generated mechanically from pinned MGC 9.7.047 V25 RAISR AOT. + * Do not edit; regenerate with + * scripts/research/generate_mgc_raisr_static_asm.py. + */ + +#if !defined(__aarch64__) +#error "MGC RAISR static lift is arm64-only" +#endif + + .hidden photon_mgc_halide_error_5f94c78 + .hidden photon_mgc_halide_error_5f94d60 + .hidden photon_mgc_halide_error_5f94e38 + .hidden photon_mgc_halide_error_5f94ec4 + .hidden photon_mgc_halide_error_5f94fa8 + .hidden photon_mgc_halide_error_5f95034 + .hidden photon_mgc_halide_error_5f950cc + .hidden photon_mgc_halide_error_5f95158 + .hidden photon_mgc_halide_error_5f95260 + .hidden photon_mgc_halide_error_5f95540 + .hidden photon_mgc_halide_error_5f95560 + .hidden photon_mgc_halide_error_5f95638 + .hidden photon_mgc_halide_error_5f956a4 + .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.Raisr.upscale_2x,"ax",@progbits + .p2align 12 + .global photon_mgc_raisr_upscale_2x + .hidden photon_mgc_raisr_upscale_2x + .type photon_mgc_raisr_upscale_2x, %function +photon_mgc_raisr_page_3589000: + .incbin "@MGC_RAISR_CAPSULE@", 0x0, 0xbf0 +photon_mgc_raisr_address_3589bf0: + .incbin "@MGC_RAISR_CAPSULE@", 0xbf0, 0xb4 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0xca4, 0x358 +photon_mgc_raisr_page_358a000: + .incbin "@MGC_RAISR_CAPSULE@", 0xffc, 0x1b8 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x11b4, 0x3c + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x11f0, 0x1c + b photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x120c, 0x20 + b photon_mgc_halide_error_5f95540 +photon_mgc_raisr_address_358a240: +photon_mgc_raisr_upscale_2x: + .incbin "@MGC_RAISR_CAPSULE@", 0x122c, 0xa4 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x12d0, 0x204 + adrp x15, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14d4, 0x40 + adrp x13, photon_mgc_raisr_page_6bf000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1514, 0x8 + adrp x13, photon_mgc_raisr_page_6c3000 + .incbin "@MGC_RAISR_CAPSULE@", 0x151c, 0x8 + adrp x13, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1524, 0x4 + adrp x13, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1528, 0x88 + adrp x16, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x15b0, 0x538 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1ae8, 0x50 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1b38, 0x24 + adrp x16, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1b5c, 0xa4 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c00, 0x3c + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c3c, 0x4 + adrp x3, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c40, 0x2c + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c6c, 0x30 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c9c, 0x34 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1cd0, 0x38 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d08, 0x4 + adrp x3, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d0c, 0x2c + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d38, 0x30 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d68, 0x34 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d9c, 0x38 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dd4, 0x4 + adrp x3, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dd8, 0x2c + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1e04, 0x28 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1e2c, 0x4 + adrp x3, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1e30, 0x2c + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1e5c, 0x124 +photon_mgc_raisr_page_358b000: + .incbin "@MGC_RAISR_CAPSULE@", 0x1f80, 0x128 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x20a8, 0x34 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x20dc, 0x2c + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2108, 0x24 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x212c, 0x20 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x214c, 0x24 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2170, 0x28 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2198, 0x38 + adrp x1, photon_mgc_raisr_page_61e7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x21d0, 0xa8 + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x2278, 0x20 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2298, 0x8 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x22a0, 0x8 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x22a8, 0x20 + b photon_mgc_halide_error_5f95560 + .incbin "@MGC_RAISR_CAPSULE@", 0x22c8, 0x4 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x22cc, 0x10 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x22dc, 0x10 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x22ec, 0xc + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x22f8, 0xc + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2304, 0xc + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2310, 0x8 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2318, 0x24 + b photon_mgc_halide_error_5f95638 + .incbin "@MGC_RAISR_CAPSULE@", 0x233c, 0x4 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2340, 0x28 + b photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x2368, 0x4 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x236c, 0x28 + b photon_mgc_halide_error_5f950cc + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2394, 0x8 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x239c, 0x8 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x23a4, 0x24 + b photon_mgc_halide_error_5f956a4 + .incbin "@MGC_RAISR_CAPSULE@", 0x23c8, 0x10 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x23d8, 0x14 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x23ec, 0x20 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x240c, 0x24 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2430, 0x4 + adrp x3, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2434, 0x14 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2448, 0xc + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2454, 0x18 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x246c, 0x14 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2480, 0x4 + adrp x3, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2484, 0x14 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2498, 0x4 + adrp x3, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x249c, 0x14 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x24b0, 0x28 + b photon_mgc_halide_error_5f94d60 + .incbin "@MGC_RAISR_CAPSULE@", 0x24d8, 0x8 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x24e0, 0x10 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x24f0, 0x20 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2510, 0x14 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2524, 0x24 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2548, 0x14 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x255c, 0x4 + adrp x3, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2560, 0x14 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2574, 0x4 + adrp x3, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2578, 0x14 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x258c, 0x24 + b photon_mgc_halide_error_5f94e38 + .incbin "@MGC_RAISR_CAPSULE@", 0x25b0, 0x8 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x25b8, 0x20 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x25d8, 0x14 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x25ec, 0x10 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x25fc, 0x24 + b photon_mgc_halide_error_5f95034 + .incbin "@MGC_RAISR_CAPSULE@", 0x2620, 0x14 + adrp x1, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2634, 0x24 + b photon_mgc_halide_error_5f94ec4 + .incbin "@MGC_RAISR_CAPSULE@", 0x2658, 0x8 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2660, 0x10 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2670, 0x10 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2680, 0x4 + adrp x3, photon_mgc_raisr_page_bb5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x2684, 0x24 + b photon_mgc_halide_error_5f95260 + .incbin "@MGC_RAISR_CAPSULE@", 0x26a8, 0x7d0 + + +.section .text.photon_mgc.Raisr.hash,"ax",@progbits + .p2align 12 + .global photon_mgc_raisr_hash + .hidden photon_mgc_raisr_hash + .type photon_mgc_raisr_hash, %function +photon_mgc_raisr_page_358f000: + .incbin "@MGC_RAISR_CAPSULE@", 0x2e78, 0x794 +photon_mgc_raisr_address_358f794: + .incbin "@MGC_RAISR_CAPSULE@", 0x360c, 0x100 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x370c, 0xec + adrp x17, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x37f8, 0x10 + adrp x17, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x3808, 0x14 + adrp x16, photon_mgc_raisr_page_6ba000 + adrp x17, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x381c, 0x33c + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x3b58, 0x308 +photon_mgc_raisr_page_3590000: + .incbin "@MGC_RAISR_CAPSULE@", 0x3e60, 0x41c + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x427c, 0x3d4 + adrp x9, photon_mgc_raisr_page_6c5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x4650, 0x47c + adrp x9, photon_mgc_raisr_page_6c6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x4acc, 0x1a0 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x4c6c, 0xc + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x4c78, 0x30 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x4ca8, 0x1a0 +photon_mgc_raisr_page_3591000: + .incbin "@MGC_RAISR_CAPSULE@", 0x4e48, 0x28 + adrp x17, photon_mgc_raisr_page_6ba000 + adrp x0, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x4e70, 0x1c + adrp x18, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x4e8c, 0x8 + adrp x1, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x4e94, 0x128 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x4fbc, 0x1e4 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x51a0, 0x338 + adrp x9, photon_mgc_raisr_page_6c5000 + .incbin "@MGC_RAISR_CAPSULE@", 0x54d8, 0x4dc + adrp x13, photon_mgc_raisr_page_6c6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x59b4, 0x1a8 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x5b5c, 0xc + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x5b68, 0x20 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x5b88, 0x28 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x5bb0, 0x18 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x5bc8, 0x14 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x5bdc, 0x30 + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x5c0c, 0xc + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x5c18, 0x8 + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x5c20, 0x8 + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x5c28, 0x18 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x5c40, 0x8 + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x5c48, 0xc + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x5c54, 0x8 + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x5c5c, 0x18 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x5c74, 0x10 + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x5c84, 0x8 + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x5c8c, 0x14 + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x5ca0, 0x20 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x5cc0, 0x20 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x5ce0, 0x18 + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x5cf8, 0x8 + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x5d00, 0xc +photon_mgc_raisr_address_3591f3c: +photon_mgc_raisr_hash: + .incbin "@MGC_RAISR_CAPSULE@", 0x5d0c, 0xc4 +photon_mgc_raisr_page_3592000: + .incbin "@MGC_RAISR_CAPSULE@", 0x5dd0, 0x158 + adrp x13, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x5f28, 0x6c + adrp x21, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x5f94, 0x24c + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x61e0, 0x34 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6214, 0x3c + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6250, 0x30 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6280, 0x20 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x62a0, 0x24 + b photon_mgc_halide_error_5f94e38 + .incbin "@MGC_RAISR_CAPSULE@", 0x62c4, 0x14 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x62d8, 0x3c + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6314, 0x198 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x64ac, 0x30 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x64dc, 0x20 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x64fc, 0x12c + adrp x1, photon_mgc_raisr_page_61e7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6628, 0x4c + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x6674, 0x20 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6694, 0x8 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x669c, 0x20 + b photon_mgc_halide_error_5f95560 + .incbin "@MGC_RAISR_CAPSULE@", 0x66bc, 0xc + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x66c8, 0x2c + b photon_mgc_halide_error_5f95158 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x66f4, 0xc + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6700, 0xc + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x670c, 0xc + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6718, 0xc + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6724, 0x28 + b photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x674c, 0x4 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6750, 0x24 + b photon_mgc_halide_error_5f950cc + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6774, 0x20 + b photon_mgc_halide_error_5f95638 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6794, 0x8 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x679c, 0x20 + b photon_mgc_halide_error_5f956a4 + .incbin "@MGC_RAISR_CAPSULE@", 0x67bc, 0x8 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x67c4, 0xc + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x67d0, 0x20 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x67f0, 0x10 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6800, 0x18 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6818, 0x28 + b photon_mgc_halide_error_5f94d60 + .incbin "@MGC_RAISR_CAPSULE@", 0x6840, 0x4 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6844, 0x18 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x685c, 0x2c + b photon_mgc_halide_error_5f94ec4 + .incbin "@MGC_RAISR_CAPSULE@", 0x6888, 0x4 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x688c, 0x28 + b photon_mgc_halide_error_5f95034 + .incbin "@MGC_RAISR_CAPSULE@", 0x68b4, 0x4 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x68b8, 0x4 + adrp x3, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x68bc, 0x14 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x68d0, 0x4 + adrp x3, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x68d4, 0x18 + adrp x1, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x68ec, 0x4 + adrp x3, photon_mgc_raisr_page_bb6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x68f0, 0x24 + b photon_mgc_halide_error_5f95260 + .incbin "@MGC_RAISR_CAPSULE@", 0x6914, 0x3f0 + + +.section .text.photon_mgc.Raisr.composite,"ax",@progbits + .p2align 12 + .global photon_mgc_raisr_composite + .hidden photon_mgc_raisr_composite + .type photon_mgc_raisr_composite, %function +photon_mgc_raisr_page_35bd000: + .incbin "@MGC_RAISR_CAPSULE@", 0x6d04, 0xdc +photon_mgc_raisr_address_35bd0dc: + .incbin "@MGC_RAISR_CAPSULE@", 0x6de0, 0x10c + adrp x13, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6eec, 0x40 + adrp x11, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6f2c, 0x8 + adrp x11, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6f34, 0xc + adrp x14, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6f40, 0xc + adrp x11, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x6f4c, 0xda4 +photon_mgc_raisr_page_35be000: + .incbin "@MGC_RAISR_CAPSULE@", 0x7cf0, 0xc9c + adrp x9, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x898c, 0xc + adrp x9, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x8998, 0x20 + adrp x9, photon_mgc_raisr_page_6ba000 + adrp x12, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x89b8, 0x328 +photon_mgc_raisr_page_35bf000: + .incbin "@MGC_RAISR_CAPSULE@", 0x8ce0, 0x998 +photon_mgc_raisr_address_35bf998: + .incbin "@MGC_RAISR_CAPSULE@", 0x9678, 0x10c + adrp x13, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x9784, 0x40 + adrp x11, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x97c4, 0x8 + adrp x11, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x97cc, 0xc + adrp x14, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x97d8, 0xc + adrp x11, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x97e4, 0x4e8 +photon_mgc_raisr_page_35c0000: + .incbin "@MGC_RAISR_CAPSULE@", 0x9ccc, 0x1000 +photon_mgc_raisr_page_35c1000: + .incbin "@MGC_RAISR_CAPSULE@", 0xaccc, 0x558 + adrp x9, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0xb224, 0xc + adrp x9, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0xb230, 0x20 + adrp x9, photon_mgc_raisr_page_6ba000 + adrp x12, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0xb250, 0xa6c +photon_mgc_raisr_page_35c2000: + .incbin "@MGC_RAISR_CAPSULE@", 0xbcbc, 0x254 +photon_mgc_raisr_address_35c2254: + .incbin "@MGC_RAISR_CAPSULE@", 0xbf10, 0xc8 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0xbfd8, 0x17c + adrp x10, photon_mgc_raisr_page_6b5000 + .incbin "@MGC_RAISR_CAPSULE@", 0xc154, 0x108 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0xc25c, 0x1b4 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0xc410, 0x1dc + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0xc5ec, 0x30 + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0xc61c, 0x10 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0xc62c, 0xc + adrp x8, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0xc638, 0x30 + b photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0xc668, 0x28 + b photon_mgc_halide_error_5f95540 +photon_mgc_raisr_address_35c29fc: + .incbin "@MGC_RAISR_CAPSULE@", 0xc690, 0x90 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0xc720, 0xdc + adrp x9, photon_mgc_raisr_page_6b7000 + .incbin "@MGC_RAISR_CAPSULE@", 0xc7fc, 0x3e0 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0xcbdc, 0x28 + adrp x8, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0xcc04, 0x28 + b photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0xcc2c, 0x20 + b photon_mgc_halide_error_5f95540 +photon_mgc_raisr_address_35c2fd0: + .incbin "@MGC_RAISR_CAPSULE@", 0xcc4c, 0x30 +photon_mgc_raisr_page_35c3000: + .incbin "@MGC_RAISR_CAPSULE@", 0xcc7c, 0x8 + adrp x3, photon_mgc_raisr_page_6bb000 + .incbin "@MGC_RAISR_CAPSULE@", 0xcc84, 0x20 + adrp x27, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0xcca4, 0x4c + adrp x26, photon_mgc_raisr_page_6bb000 + .incbin "@MGC_RAISR_CAPSULE@", 0xccf0, 0x8 + adrp x28, photon_mgc_raisr_page_6c4000 + .incbin "@MGC_RAISR_CAPSULE@", 0xccf8, 0x1c + adrp x11, photon_mgc_raisr_page_6b2000 + .incbin "@MGC_RAISR_CAPSULE@", 0xcd14, 0xf54 +photon_mgc_raisr_page_35c4000: + .incbin "@MGC_RAISR_CAPSULE@", 0xdc68, 0xa44 +photon_mgc_raisr_address_35c4a44: + .incbin "@MGC_RAISR_CAPSULE@", 0xe6ac, 0x74 + adrp x18, photon_mgc_raisr_page_6bb000 + .incbin "@MGC_RAISR_CAPSULE@", 0xe720, 0x4 + adrp x1, photon_mgc_raisr_page_6c4000 + .incbin "@MGC_RAISR_CAPSULE@", 0xe724, 0x4 + adrp x18, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0xe728, 0x8 + adrp x1, photon_mgc_raisr_page_6bb000 + .incbin "@MGC_RAISR_CAPSULE@", 0xe730, 0x528 +photon_mgc_raisr_page_35c5000: + .incbin "@MGC_RAISR_CAPSULE@", 0xec58, 0x1000 +photon_mgc_raisr_page_35c6000: + .incbin "@MGC_RAISR_CAPSULE@", 0xfc58, 0x4e4 +photon_mgc_raisr_address_35c64e4: + .incbin "@MGC_RAISR_CAPSULE@", 0x1013c, 0xa8 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x101e4, 0x178 + adrp x9, photon_mgc_raisr_page_6b7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1035c, 0xcc + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x10428, 0x1a0 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x105c8, 0x1dc + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x107a4, 0x34 + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x107d8, 0x18 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x107f0, 0x14 + adrp x8, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x10804, 0x30 + b photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x10834, 0x2c + b photon_mgc_halide_error_5f95540 +photon_mgc_raisr_address_35c6c30: + .incbin "@MGC_RAISR_CAPSULE@", 0x10860, 0x60 + adrp x15, photon_mgc_raisr_page_6bb000 + .incbin "@MGC_RAISR_CAPSULE@", 0x108c0, 0x4 + adrp x18, photon_mgc_raisr_page_6c4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x108c4, 0x14 + adrp x15, photon_mgc_raisr_page_6bc000 + adrp x18, photon_mgc_raisr_page_6bb000 + .incbin "@MGC_RAISR_CAPSULE@", 0x108d8, 0x348 +photon_mgc_raisr_page_35c7000: + .incbin "@MGC_RAISR_CAPSULE@", 0x10c20, 0x1000 +photon_mgc_raisr_page_35c8000: + .incbin "@MGC_RAISR_CAPSULE@", 0x11c20, 0x6a0 +photon_mgc_raisr_address_35c86a0: + .incbin "@MGC_RAISR_CAPSULE@", 0x122c0, 0x5b4 +photon_mgc_raisr_address_35c8c54: +photon_mgc_raisr_composite: + .incbin "@MGC_RAISR_CAPSULE@", 0x12874, 0xbc + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x12930, 0x240 + adrp x19, photon_mgc_raisr_page_6b6000 + .incbin "@MGC_RAISR_CAPSULE@", 0x12b70, 0xa8 +photon_mgc_raisr_page_35c9000: + .incbin "@MGC_RAISR_CAPSULE@", 0x12c18, 0x74 + adrp x20, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x12c8c, 0x48 + adrp x19, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x12cd4, 0x54 + adrp x25, photon_mgc_raisr_page_6bf000 + .incbin "@MGC_RAISR_CAPSULE@", 0x12d28, 0xd8 + adrp x27, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x12e00, 0x378 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x13178, 0x4c + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x131c4, 0x44 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x13208, 0x3c + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x13244, 0x4 + adrp x3, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x13248, 0x30 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x13278, 0x2c + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x132a4, 0x34 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x132d8, 0x224 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x134fc, 0x30 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1352c, 0x20 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1354c, 0x28 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x13574, 0x18 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1358c, 0x20 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x135ac, 0x20 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x135cc, 0x24 + adrp x8, photon_mgc_raisr_page_6b9000 + .incbin "@MGC_RAISR_CAPSULE@", 0x135f0, 0xc + adrp x8, photon_mgc_raisr_page_6b8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x135fc, 0x204 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x13800, 0x1c + adrp x1, photon_mgc_raisr_page_61e7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1381c, 0x80 + adrp x9, photon_mgc_raisr_page_6c0000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1389c, 0x24 + adrp x8, photon_mgc_raisr_page_6bb000 + .incbin "@MGC_RAISR_CAPSULE@", 0x138c0, 0x4c + adrp x11, photon_mgc_raisr_page_6c4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1390c, 0xf4 + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x13a00, 0x70 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x13a70, 0x20 + adrp x1, photon_mgc_raisr_page_61e7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x13a90, 0x114 +photon_mgc_raisr_page_35ca000: + .incbin "@MGC_RAISR_CAPSULE@", 0x13ba4, 0x94 + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x13c38, 0x154 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x13d8c, 0x1c + adrp x1, photon_mgc_raisr_page_61e7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x13da8, 0x88 + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x13e30, 0x14 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x13e44, 0x11c + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x13f60, 0x28 + adrp x1, photon_mgc_raisr_page_61e7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x13f88, 0x84 + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x1400c, 0x10 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x1401c, 0x8c + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x140a8, 0x1c + adrp x1, photon_mgc_raisr_page_61e7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x140c4, 0x70 + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x14134, 0x14 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x14148, 0x50 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x14198, 0x1c + adrp x1, photon_mgc_raisr_page_61e7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x141b4, 0xe8 + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x1429c, 0x14 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x142b0, 0x68 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x14318, 0x14 + adrp x1, photon_mgc_raisr_page_61e7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1432c, 0xbc + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x143e8, 0x14 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x143fc, 0x8 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x14404, 0x1c + adrp x1, photon_mgc_raisr_page_61e7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14420, 0x90 + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x144b0, 0x1c + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x144cc, 0xd4 + adrp x1, photon_mgc_raisr_page_61e7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x145a0, 0x48 + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x145e8, 0x10 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x145f8, 0xc + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x14604, 0x40 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x14644, 0x18 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x1465c, 0x24 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x14680, 0x24 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x146a4, 0x24 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x146c8, 0x24 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x146ec, 0x24 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x14710, 0x40 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14750, 0x8 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14758, 0x8 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14760, 0x34 + b photon_mgc_halide_error_5f95560 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14794, 0x10 + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x147a4, 0x24 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x147c8, 0x10 + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x147d8, 0x14 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x147ec, 0x10 + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x147fc, 0x38 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14834, 0x10 + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x14844, 0x34 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14878, 0x10 + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x14888, 0x14 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1489c, 0x10 + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x148ac, 0x28 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x148d4, 0x10 + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x148e4, 0x48 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x1492c, 0x4c + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x14978, 0x40 + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x149b8, 0x3c + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x149f4, 0x1c + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x14a10, 0x18 + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x14a28, 0x3c + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x14a64, 0x24 + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x14a88, 0x24 +photon_mgc_raisr_page_35cb000: + .incbin "@MGC_RAISR_CAPSULE@", 0x14aac, 0x10 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14abc, 0x8 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14ac4, 0x18 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14adc, 0x10 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14aec, 0x18 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14b04, 0xc + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14b10, 0x18 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14b28, 0x18 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14b40, 0x14 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14b54, 0x38 + b photon_mgc_halide_error_5f94e38 + .incbin "@MGC_RAISR_CAPSULE@", 0x14b8c, 0x4 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14b90, 0x3c + b photon_mgc_halide_error_5f94d60 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14bcc, 0x1c + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14be8, 0x18 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14c00, 0x3c + b photon_mgc_halide_error_5f95034 + .incbin "@MGC_RAISR_CAPSULE@", 0x14c3c, 0x10 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14c4c, 0x38 + b photon_mgc_halide_error_5f94ec4 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14c84, 0x4 + adrp x3, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14c88, 0x14 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14c9c, 0x4 + adrp x3, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14ca0, 0xc + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14cac, 0x4 + adrp x3, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14cb0, 0x3c + b photon_mgc_halide_error_5f95260 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14cec, 0x10 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14cfc, 0x10 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14d0c, 0x10 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14d1c, 0x8 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14d24, 0x3c + b photon_mgc_halide_error_5f950cc + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14d60, 0x34 + b photon_mgc_halide_error_5f95638 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14d94, 0x10 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14da4, 0x3c + b photon_mgc_halide_error_5f94fa8 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14de0, 0x8 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14de8, 0x8 + adrp x1, photon_mgc_raisr_page_bb8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x14df0, 0x34 + b photon_mgc_halide_error_5f956a4 + .incbin "@MGC_RAISR_CAPSULE@", 0x14e24, 0xbe8 + + +.section .text.photon_mgc.Raisr.orientation,"ax",@progbits + .p2align 12 + .global photon_mgc_raisr_orientation + .hidden photon_mgc_raisr_orientation + .type photon_mgc_raisr_orientation, %function +photon_mgc_raisr_page_359b000: + .incbin "@MGC_RAISR_CAPSULE@", 0x15a0c, 0xa8 +photon_mgc_raisr_address_359b0a8: + .incbin "@MGC_RAISR_CAPSULE@", 0x15ab4, 0x12c + adrp x16, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x15be0, 0x4c + adrp x18, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x15c2c, 0x10 + adrp x18, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x15c3c, 0x20 + adrp x16, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x15c5c, 0x34 + adrp x17, photon_mgc_raisr_page_6c2000 + .incbin "@MGC_RAISR_CAPSULE@", 0x15c90, 0xad8 + adrp x13, photon_mgc_raisr_page_6c2000 + .incbin "@MGC_RAISR_CAPSULE@", 0x16768, 0x28c +photon_mgc_raisr_page_359c000: + .incbin "@MGC_RAISR_CAPSULE@", 0x169f4, 0x408 + adrp x16, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x16dfc, 0x28 + adrp x14, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x16e24, 0x8 + adrp x15, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x16e2c, 0x14 + adrp x9, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x16e40, 0x24 + adrp x10, photon_mgc_raisr_page_6c2000 + .incbin "@MGC_RAISR_CAPSULE@", 0x16e64, 0xac8 + adrp x3, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1792c, 0x8 + adrp x7, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x17934, 0x8c + adrp x19, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x179c0, 0x4 + adrp x4, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x179c4, 0xc +photon_mgc_raisr_page_359d000: + .incbin "@MGC_RAISR_CAPSULE@", 0x179d0, 0x1c + adrp x16, photon_mgc_raisr_page_6c2000 + .incbin "@MGC_RAISR_CAPSULE@", 0x179ec, 0xad4 +photon_mgc_raisr_address_359daf4: +photon_mgc_raisr_orientation: + .incbin "@MGC_RAISR_CAPSULE@", 0x184c0, 0x2a4 + adrp x25, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18764, 0x5c + adrp x25, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x187c0, 0x204 +photon_mgc_raisr_page_359e000: + .incbin "@MGC_RAISR_CAPSULE@", 0x189c4, 0x54 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18a18, 0x34 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18a4c, 0x28 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18a74, 0x34 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18aa8, 0x2c + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18ad4, 0x38 + b photon_mgc_halide_error_5f94e38 + .incbin "@MGC_RAISR_CAPSULE@", 0x18b0c, 0x14 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18b20, 0x20 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18b40, 0x1e4 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18d24, 0x2c + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18d50, 0x28 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18d78, 0x28 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18da0, 0x18 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x18db8, 0x88 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x18e40, 0x3c + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x18e7c, 0x54 + bl photon_mgc_halide_malloc + .incbin "@MGC_RAISR_CAPSULE@", 0x18ed0, 0x130 + adrp x8, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x19000, 0x4 + adrp x8, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x19004, 0x4 + adrp x8, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x19008, 0x4 + adrp x8, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1900c, 0x968 +photon_mgc_raisr_page_359f000: + .incbin "@MGC_RAISR_CAPSULE@", 0x19974, 0x90 + adrp x9, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x19a04, 0x4 + adrp x9, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x19a08, 0x4 + adrp x9, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x19a0c, 0x4 + adrp x9, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x19a10, 0xf54 +photon_mgc_raisr_page_35a0000: + .incbin "@MGC_RAISR_CAPSULE@", 0x1a964, 0x220 + adrp x8, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1ab84, 0x4 + adrp x8, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1ab88, 0x4 + adrp x8, photon_mgc_raisr_page_6ba000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1ab8c, 0x4 + adrp x8, photon_mgc_raisr_page_6bc000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1ab90, 0x8cc + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x1b45c, 0x8 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x1b464, 0x4e8 +photon_mgc_raisr_page_35a1000: + .incbin "@MGC_RAISR_CAPSULE@", 0x1b94c, 0x688 + adrp x1, photon_mgc_raisr_page_61e7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1bfd4, 0xc + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x1bfe0, 0x10 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x1bff0, 0x20 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x1c010, 0x30 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c040, 0xc + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c04c, 0x8 + bl photon_mgc_halide_error_5f95560 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c054, 0x8 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c05c, 0xc + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c068, 0xc + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c074, 0x4 + adrp x2, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c078, 0x10 + bl photon_mgc_halide_error_5f94c78 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c088, 0x20 + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c0a8, 0x4 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c0ac, 0xc + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c0b8, 0x18 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c0d0, 0xc + bl photon_mgc_halide_error_5f94fa8 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c0dc, 0x18 + bl photon_mgc_halide_error_5f95540 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c0f4, 0x14 + bl photon_mgc_halide_free + .incbin "@MGC_RAISR_CAPSULE@", 0x1c108, 0xc + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c114, 0x10 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c124, 0x10 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c134, 0x38 + b photon_mgc_halide_error_5f950cc + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c16c, 0x10 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c17c, 0x18 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c194, 0x1c + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c1b0, 0x1c + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c1cc, 0x10 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c1dc, 0x3c + b photon_mgc_halide_error_5f94d60 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c218, 0x4 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c21c, 0x24 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c240, 0x3c + b photon_mgc_halide_error_5f94ec4 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c27c, 0x38 + b photon_mgc_halide_error_5f95034 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c2b4, 0x4 + adrp x3, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c2b8, 0x10 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c2c8, 0x4 + adrp x3, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c2cc, 0x34 + b photon_mgc_halide_error_5f95260 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c300, 0x10 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c310, 0x30 + b photon_mgc_halide_error_5f95638 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c340, 0x38 + b photon_mgc_halide_error_5f94fa8 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c378, 0x8 + adrp x1, photon_mgc_raisr_page_bb7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c380, 0x30 + b photon_mgc_halide_error_5f956a4 + .incbin "@MGC_RAISR_CAPSULE@", 0x1c3b0, 0x4dc + + +.section .text.photon_mgc.Raisr.rgb_to_gray,"ax",@progbits + .p2align 12 + .global photon_mgc_raisr_rgb_to_gray + .hidden photon_mgc_raisr_rgb_to_gray + .type photon_mgc_raisr_rgb_to_gray, %function +photon_mgc_raisr_page_3c50000: + .incbin "@MGC_RAISR_CAPSULE@", 0x1c88c, 0xbc8 +photon_mgc_raisr_address_3c50bc8: + .incbin "@MGC_RAISR_CAPSULE@", 0x1d454, 0xf4 +photon_mgc_raisr_address_3c50cbc: +photon_mgc_raisr_rgb_to_gray: + .incbin "@MGC_RAISR_CAPSULE@", 0x1d548, 0xb0 + adrp x28, photon_mgc_raisr_page_6b7000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d5f8, 0x10 + adrp x27, photon_mgc_raisr_page_6c0000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d608, 0x44 + adrp x29, photon_mgc_raisr_page_6b4000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d64c, 0x234 +photon_mgc_raisr_page_3c51000: + .incbin "@MGC_RAISR_CAPSULE@", 0x1d880, 0x8 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d888, 0x38 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d8c0, 0x30 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d8f0, 0x30 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d920, 0x4 + adrp x3, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d924, 0x20 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d944, 0x24 + b photon_mgc_halide_error_5f94e38 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d968, 0x18 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d980, 0x24 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d9a4, 0x28 + b photon_mgc_halide_error_5f95034 + .incbin "@MGC_RAISR_CAPSULE@", 0x1d9cc, 0x160 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1db2c, 0x30 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1db5c, 0x28 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1db84, 0x5c + adrp x1, photon_mgc_raisr_page_61e8000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dbe0, 0x28 + bl photon_mgc_halide_do_par_for + .incbin "@MGC_RAISR_CAPSULE@", 0x1dc08, 0x20 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dc28, 0x8 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dc30, 0x20 + b photon_mgc_halide_error_5f95560 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dc50, 0x4 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dc54, 0x10 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dc64, 0x10 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dc74, 0x8 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dc7c, 0x28 + b photon_mgc_halide_error_5f950cc + .incbin "@MGC_RAISR_CAPSULE@", 0x1dca4, 0x4 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dca8, 0x28 + b photon_mgc_halide_error_5f94fa8 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dcd0, 0x24 + b photon_mgc_halide_error_5f95638 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dcf4, 0x8 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dcfc, 0x24 + b photon_mgc_halide_error_5f956a4 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dd20, 0x8 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dd28, 0x18 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dd40, 0x24 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dd64, 0x28 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dd8c, 0x4 + adrp x3, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dd90, 0x10 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1dda0, 0x2c + b photon_mgc_halide_error_5f94d60 + .incbin "@MGC_RAISR_CAPSULE@", 0x1ddcc, 0x8 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1ddd4, 0x24 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1ddf8, 0x2c + b photon_mgc_halide_error_5f94ec4 + .incbin "@MGC_RAISR_CAPSULE@", 0x1de24, 0x4 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1de28, 0x4 + adrp x3, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1de2c, 0x14 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1de40, 0x4 + adrp x3, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1de44, 0x14 + adrp x1, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1de58, 0x4 + adrp x3, photon_mgc_raisr_page_c32000 + .incbin "@MGC_RAISR_CAPSULE@", 0x1de5c, 0x28 + b photon_mgc_halide_error_5f95260 + .incbin "@MGC_RAISR_CAPSULE@", 0x1de84, 0x940 + +.section .rodata.photon_mgc.raisr_page_6b2000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6b2000: + .incbin "@MGC_RAISR_CAPSULE@", 0x1e7c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6b4000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6b4000: + .incbin "@MGC_RAISR_CAPSULE@", 0x1f7c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6b5000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6b5000: + .incbin "@MGC_RAISR_CAPSULE@", 0x207c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6b6000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6b6000: + .incbin "@MGC_RAISR_CAPSULE@", 0x217c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6b7000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6b7000: + .incbin "@MGC_RAISR_CAPSULE@", 0x227c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6b8000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6b8000: + .incbin "@MGC_RAISR_CAPSULE@", 0x237c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6b9000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6b9000: + .incbin "@MGC_RAISR_CAPSULE@", 0x247c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6ba000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6ba000: + .incbin "@MGC_RAISR_CAPSULE@", 0x257c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6bb000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6bb000: + .incbin "@MGC_RAISR_CAPSULE@", 0x267c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6bc000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6bc000: + .incbin "@MGC_RAISR_CAPSULE@", 0x277c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6bf000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6bf000: + .incbin "@MGC_RAISR_CAPSULE@", 0x287c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6c0000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6c0000: + .incbin "@MGC_RAISR_CAPSULE@", 0x297c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6c2000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6c2000: + .incbin "@MGC_RAISR_CAPSULE@", 0x2a7c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6c3000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6c3000: + .incbin "@MGC_RAISR_CAPSULE@", 0x2b7c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6c4000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6c4000: + .incbin "@MGC_RAISR_CAPSULE@", 0x2c7c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6c5000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6c5000: + .incbin "@MGC_RAISR_CAPSULE@", 0x2d7c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_6c6000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_6c6000: + .incbin "@MGC_RAISR_CAPSULE@", 0x2e7c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_bb5000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_bb5000: + .incbin "@MGC_RAISR_CAPSULE@", 0x2f7c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_bb6000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_bb6000: + .incbin "@MGC_RAISR_CAPSULE@", 0x307c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_bb7000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_bb7000: + .incbin "@MGC_RAISR_CAPSULE@", 0x317c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_bb8000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_bb8000: + .incbin "@MGC_RAISR_CAPSULE@", 0x327c4, 0x1000 + +.section .rodata.photon_mgc.raisr_page_c32000,"a",@progbits + .p2align 12 +photon_mgc_raisr_page_c32000: + .incbin "@MGC_RAISR_CAPSULE@", 0x337c4, 0x1000 + +.section .data.rel.ro.photon_mgc.raisr_page_61e7000,"aw",@progbits + .p2align 12 +photon_mgc_raisr_page_61e7000: + .incbin "@MGC_RAISR_CAPSULE@", 0x347c4, 0x68 + .xword photon_mgc_raisr_address_3589bf0 + .incbin "@MGC_RAISR_CAPSULE@", 0x3482c, 0x10 + .xword photon_mgc_raisr_address_358f794 + .incbin "@MGC_RAISR_CAPSULE@", 0x3483c, 0x10 + .xword photon_mgc_raisr_address_359b0a8 + .incbin "@MGC_RAISR_CAPSULE@", 0x3484c, 0x80 + .xword photon_mgc_raisr_address_35bd0dc + .xword photon_mgc_raisr_address_35bf998 + .xword photon_mgc_raisr_address_35c2254 + .xword photon_mgc_raisr_address_35c29fc + .xword photon_mgc_raisr_address_35c2fd0 + .xword photon_mgc_raisr_address_35c4a44 + .xword photon_mgc_raisr_address_35c64e4 + .xword photon_mgc_raisr_address_35c6c30 + .xword photon_mgc_raisr_address_35c86a0 + .incbin "@MGC_RAISR_CAPSULE@", 0x348cc, 0xe98 + +.section .data.rel.ro.photon_mgc.raisr_page_61e8000,"aw",@progbits + .p2align 12 +photon_mgc_raisr_page_61e8000: + .incbin "@MGC_RAISR_CAPSULE@", 0x35764, 0x630 + .xword photon_mgc_raisr_address_3c50bc8 + .incbin "@MGC_RAISR_CAPSULE@", 0x35d94, 0x9c8 + +.section .note.GNU-stack,"",@progbits diff --git a/app/src/main/cpp/mgc_denoise_static/mgc_raisr_tables_static.S.in b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_tables_static.S.in new file mode 100644 index 00000000..f19878c2 --- /dev/null +++ b/app/src/main/cpp/mgc_denoise_static/mgc_raisr_tables_static.S.in @@ -0,0 +1,34 @@ +/* MGC V25 RAISR static tables, lifted from the pinned libgcastartup.so. + * + * Regenerate the .bin assets with + * scripts/research/extract_mgc_raisr_filters.py + * scripts/research/extract_mgc_raisr_randomness_lut.py + * + * photon_mgc_raisr_filters: 216 classes x 25 taps x 4 shifts of int16 (Q12), + * indexed shift*5400 + cls*25 + ky*5 + kx. + * photon_mgc_raisr_randomness_lut: 16x16 dither levels {0, 5, 10, 15}. + */ + +#if !defined(__aarch64__) +#error "MGC RAISR static tables are arm64-only" +#endif + +.section .rodata.photon_mgc_raisr_tables,"a",@progbits + +.p2align 6 +.global photon_mgc_raisr_filters +.hidden photon_mgc_raisr_filters +.type photon_mgc_raisr_filters, %object +photon_mgc_raisr_filters: + .incbin "@MGC_RAISR_FILTERS@" +.size photon_mgc_raisr_filters, 43200 + +.p2align 6 +.global photon_mgc_raisr_randomness_lut +.hidden photon_mgc_raisr_randomness_lut +.type photon_mgc_raisr_randomness_lut, %object +photon_mgc_raisr_randomness_lut: + .incbin "@MGC_RAISR_RANDOMNESS_LUT@" +.size photon_mgc_raisr_randomness_lut, 256 + +.section .note.GNU-stack,"",@progbits diff --git a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt index 71eaa91c..bc5a91d1 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt @@ -69,6 +69,7 @@ import com.hinnka.mycamera.mgc.PhotonLookContract import com.hinnka.mycamera.processor.DenoiseStrength import com.hinnka.mycamera.processor.PhotonSensorSizeTuning import com.hinnka.mycamera.processor.MgcRawMaxMode +import com.hinnka.mycamera.raw.RawOutputUpscaleMode import org.json.JSONObject /** @@ -205,6 +206,7 @@ data class UserPreferences( val hdrPlusBracketExposureEnabled: Boolean = MultiFrameConfig.DEFAULT_HDR_PLUS_BRACKET_EXPOSURE, val rawMaxOutputScale: Float = MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE, // RAWmax 输出倍率 + val rawOutputUpscaleMode: RawOutputUpscaleMode = RawOutputUpscaleMode.DEFAULT, // RAWmax 输出放大算法 val rawDigitalZoomResamplingEnabled: Boolean = false, val photoQuality: Int = 95, // 照片质量: 90, 95, 100 val useHeicExport: Boolean = false, // 是否优先使用 HEIC 导出 @@ -471,6 +473,7 @@ class UserPreferencesRepository(private val context: Context) { private val MULTIPLE_EXPOSURE_COUNT = intPreferencesKey("multiple_exposure_count") private val LEGACY_USE_SUPER_RESOLUTION = booleanPreferencesKey("use_super_resolution") private val RAW_MAX_OUTPUT_SCALE = floatPreferencesKey("raw_max_output_scale") + private val RAW_OUTPUT_UPSCALE_MODE = stringPreferencesKey("raw_output_upscale_mode") private val RAW_DIGITAL_ZOOM_RESAMPLING_ENABLED = booleanPreferencesKey("raw_digital_zoom_resampling_enabled") private val LEGACY_RAW_SUPER_RESOLUTION_SCALE = floatPreferencesKey("raw_super_resolution_scale") @@ -604,6 +607,8 @@ class UserPreferencesRepository(private val context: Context) { val hdrPlusMergeMode = MgcRawMaxMode.entries.firstOrNull { it.name == preferences[HDR_PLUS_MERGE_MODE] } ?: MgcRawMaxMode.DEFAULT + val rawOutputUpscaleMode = + RawOutputUpscaleMode.fromName(preferences[RAW_OUTPUT_UPSCALE_MODE]) val hdrPlusBracketExposureEnabled = hdrPlusMergeMode.supportsBracketExposure && (preferences[HDR_PLUS_BRACKET_EXPOSURE_ENABLED] ?: MultiFrameConfig.DEFAULT_HDR_PLUS_BRACKET_EXPOSURE) @@ -793,13 +798,16 @@ class UserPreferencesRepository(private val context: Context) { } ?: MultiFrameConfig.DEFAULT_HDR_PLUS_FRAME_COUNT, hdrPlusBracketExposureEnabled = hdrPlusBracketExposureEnabled, - rawMaxOutputScale = (preferences[RAW_MAX_OUTPUT_SCALE] - ?: preferences[LEGACY_RAW_SUPER_RESOLUTION_SCALE])?.let { - MultiFrameConfig.normalizeOutputScale( - outputScale = it, - fallback = MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE, - ) - } ?: MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE, + rawMaxOutputScale = rawOutputUpscaleMode.resolveOutputScale( + (preferences[RAW_MAX_OUTPUT_SCALE] + ?: preferences[LEGACY_RAW_SUPER_RESOLUTION_SCALE])?.let { + MultiFrameConfig.normalizeOutputScale( + outputScale = it, + fallback = MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE, + ) + } ?: MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE + ), + rawOutputUpscaleMode = rawOutputUpscaleMode, rawDigitalZoomResamplingEnabled = preferences[RAW_DIGITAL_ZOOM_RESAMPLING_ENABLED] ?: false, photoQuality = preferences[PHOTO_QUALITY] ?: 95, @@ -2067,10 +2075,19 @@ class UserPreferencesRepository(private val context: Context) { suspend fun saveRawMaxOutputScale(scale: Float) { context.dataStore.edit { preferences -> - preferences[RAW_MAX_OUTPUT_SCALE] = MultiFrameConfig.normalizeOutputScale( - outputScale = scale, - fallback = MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE, - ) + preferences[RAW_MAX_OUTPUT_SCALE] = RawOutputUpscaleMode.fromName( + preferences[RAW_OUTPUT_UPSCALE_MODE] + ).resolveOutputScale(scale) + } + } + + /** + * 保存 RAWmax 输出放大算法。RAISR 自带 per-shift 放大倍率,选中时把输出倍率锁定到 2x。 + */ + suspend fun saveRawOutputUpscaleMode(mode: RawOutputUpscaleMode) { + context.dataStore.edit { preferences -> + preferences[RAW_OUTPUT_UPSCALE_MODE] = mode.name + mode.pinnedOutputScale?.let { preferences[RAW_MAX_OUTPUT_SCALE] = it } } } diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt index 72b07688..f66f7bfd 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt @@ -2401,6 +2401,7 @@ object GalleryManager { rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode, rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop, rawOutputScale = RawOutputScaling.read(updatedMetadata.customProperties), + rawOutputUpscaleMode = updatedMetadata.rawOutputUpscaleMode, rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(updatedMetadata.customProperties), spectralFilmStock = updatedMetadata.spectralFilmStock, spectralFilmPrint = updatedMetadata.spectralFilmPrint, @@ -2497,6 +2498,7 @@ object GalleryManager { rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode, rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop, rawOutputScale = RawOutputScaling.read(updatedMetadata.customProperties), + rawOutputUpscaleMode = updatedMetadata.rawOutputUpscaleMode, rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(updatedMetadata.customProperties), spectralFilmStock = updatedMetadata.spectralFilmStock, spectralFilmPrint = updatedMetadata.spectralFilmPrint, @@ -3574,6 +3576,7 @@ object GalleryManager { metadata.customProperties, physicalRawCrop, metadata.rawBlackBorderCrop, ), rawStackOutputScale, + metadata.rawOutputUpscaleMode, ), // These fields describe the processor-specific FinishRaw denoise already // baked into LinearRaw; the merge itself remains represented by the pixels. @@ -3743,6 +3746,7 @@ object GalleryManager { rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode, rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop, rawOutputScale = RawOutputScaling.read(updatedMetadata.customProperties), + rawOutputUpscaleMode = updatedMetadata.rawOutputUpscaleMode, rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(updatedMetadata.customProperties), spectralFilmStock = updatedMetadata.spectralFilmStock, spectralFilmPrint = updatedMetadata.spectralFilmPrint, @@ -3837,6 +3841,7 @@ object GalleryManager { rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode, rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop, rawOutputScale = RawOutputScaling.read(updatedMetadata.customProperties), + rawOutputUpscaleMode = updatedMetadata.rawOutputUpscaleMode, rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(updatedMetadata.customProperties), spectralFilmStock = updatedMetadata.spectralFilmStock, spectralFilmPrint = updatedMetadata.spectralFilmPrint, @@ -4121,6 +4126,7 @@ object GalleryManager { rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode, rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop, rawOutputScale = RawOutputScaling.read(updatedMetadata.customProperties), + rawOutputUpscaleMode = updatedMetadata.rawOutputUpscaleMode, rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(updatedMetadata.customProperties), spectralFilmStock = updatedMetadata.spectralFilmStock, spectralFilmPrint = updatedMetadata.spectralFilmPrint, @@ -5574,6 +5580,7 @@ object GalleryManager { rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode, rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop, rawOutputScale = RawOutputScaling.read(updatedMetadata.customProperties), + rawOutputUpscaleMode = updatedMetadata.rawOutputUpscaleMode, rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(updatedMetadata.customProperties), spectralFilmStock = updatedMetadata.spectralFilmStock, spectralFilmPrint = updatedMetadata.spectralFilmPrint, @@ -5767,6 +5774,7 @@ object GalleryManager { rawCfaCorrectionMode = updatedMetadata?.rawCfaCorrectionMode, rawBlackBorderCrop = rawMetadata.rawBlackBorderCrop, rawOutputScale = RawOutputScaling.read(rawMetadata.customProperties), + rawOutputUpscaleMode = rawMetadata.rawOutputUpscaleMode, rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(rawMetadata.customProperties), spectralFilmStock = updatedMetadata?.spectralFilmStock, spectralFilmPrint = updatedMetadata?.spectralFilmPrint, diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt b/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt index b6a479e1..1454525c 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt @@ -21,6 +21,7 @@ import com.hinnka.mycamera.raw.LumixPhotoStyle import com.hinnka.mycamera.raw.CanonPictureStyle import com.hinnka.mycamera.raw.RawRenderingEngine import com.hinnka.mycamera.raw.RawToneMappingParameters +import com.hinnka.mycamera.raw.RawOutputUpscaleMode import com.hinnka.mycamera.raw.RawCaptureExposureCompensationMetadata import com.hinnka.mycamera.utils.DeviceUtil import org.json.JSONObject @@ -79,6 +80,8 @@ data class MediaMetadata( val rawHncsFilmCurveMode: HncsFilmCurveMode = HncsFilmCurveMode.Standard, val rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve, val rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT, + /** Professional-mode output magnification algorithm used for this capture. */ + val rawOutputUpscaleMode: RawOutputUpscaleMode = RawOutputUpscaleMode.DEFAULT, val cameraId: String? = null, // 边框水印配置 val frameId: String? = null, @@ -352,6 +355,11 @@ data class MediaMetadata( if (obj.isNull("rawColorEngine")) null else obj.optString("rawColorEngine"), fallback = RawRenderingEngine.AdobeCurve ), + // Absent on older photos, which were all magnified with Lanczos-3. + rawOutputUpscaleMode = RawOutputUpscaleMode.fromName( + if (obj.isNull("rawOutputUpscaleMode")) null + else obj.optString("rawOutputUpscaleMode") + ), rawToneMappingParameters = RawToneMappingParameters( agxBlackRelativeExposure = if (obj.isNull("rawAgxBlackRelativeExposure")) { RawToneMappingParameters.AGX_BLACK_RELATIVE_EXPOSURE_DEFAULT diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt index 5cc3cd28..b5f91184 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt @@ -607,6 +607,7 @@ class PhotoProcessor( rawCfaCorrectionMode = metadata.rawCfaCorrectionMode, rawBlackBorderCrop = metadata.rawBlackBorderCrop, rawOutputScale = RawOutputScaling.read(metadata.customProperties), + rawOutputUpscaleMode = metadata.rawOutputUpscaleMode, rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(metadata.customProperties), spectralFilmStock = metadata.spectralFilmStock, spectralFilmPrint = metadata.spectralFilmPrint, @@ -693,6 +694,7 @@ class PhotoProcessor( rawCfaCorrectionMode = metadata.rawCfaCorrectionMode, rawBlackBorderCrop = metadata.rawBlackBorderCrop, rawOutputScale = RawOutputScaling.read(metadata.customProperties), + rawOutputUpscaleMode = metadata.rawOutputUpscaleMode, rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(metadata.customProperties), spectralFilmStock = metadata.spectralFilmStock, spectralFilmPrint = metadata.spectralFilmPrint, diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryDatabase.kt b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryDatabase.kt index 0bc6e55a..c41ab2d8 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryDatabase.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryDatabase.kt @@ -8,7 +8,7 @@ import com.hinnka.mycamera.raw.RawToneMappingParameters @Database( entities = [GalleryMediaEntity::class], - version = 45, + version = 46, exportSchema = false ) @androidx.room.TypeConverters(GalleryConverters::class) @@ -804,6 +804,16 @@ abstract class GalleryDatabase : RoomDatabase() { } } + private val MIGRATION_45_46 = object : androidx.room.migration.Migration(45, 46) { + override fun migrate(db: androidx.sqlite.db.SupportSQLiteDatabase) { + // Photos captured before the setting existed were all magnified with + // the Lanczos-3 path, so Lanczos-3 is the correct backfill. + db.execSQL( + "ALTER TABLE gallery_media ADD COLUMN rawOutputUpscaleMode TEXT NOT NULL DEFAULT 'LANCZOS3'" + ) + } + } + fun getInstance(context: Context): GalleryDatabase { return INSTANCE ?: synchronized(this) { INSTANCE ?: Room.databaseBuilder( @@ -855,7 +865,8 @@ abstract class GalleryDatabase : RoomDatabase() { MIGRATION_41_42, MIGRATION_42_43, MIGRATION_43_44, - MIGRATION_44_45 + MIGRATION_44_45, + MIGRATION_45_46 ) .fallbackToDestructiveMigrationOnDowngrade(false) .fallbackToDestructiveMigration(false) diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaEntity.kt b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaEntity.kt index 25110567..29be0aae 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaEntity.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaEntity.kt @@ -62,6 +62,9 @@ data class GalleryMediaEntity( val rawHncsRenderIntent: String = "standard", val rawHncsFilmCurveMode: String = "standard", val rawColorEngine: String, + /** Professional-mode output magnification algorithm; absent on older rows. */ + @ColumnInfo(defaultValue = "'LANCZOS3'") + val rawOutputUpscaleMode: String = "LANCZOS3", @ColumnInfo(defaultValue = "'standard'") val rawLumixPhotoStyle: String = "standard", @ColumnInfo(defaultValue = "'standard'") diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaStore.kt b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaStore.kt index fb9ea6a7..1cad377e 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaStore.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaStore.kt @@ -19,6 +19,7 @@ import com.hinnka.mycamera.raw.HncsRenderIntent import com.hinnka.mycamera.raw.HncsProfileManager import com.hinnka.mycamera.raw.LumixPhotoStyle import com.hinnka.mycamera.raw.CanonPictureStyle +import com.hinnka.mycamera.raw.RawOutputUpscaleMode import com.hinnka.mycamera.raw.RawRenderingEngine import com.hinnka.mycamera.raw.RawToneMappingParameters import com.hinnka.mycamera.raw.RawAdaptiveExposureMode @@ -243,6 +244,7 @@ object GalleryMediaStore { rawHncsRenderIntent = metadata.rawHncsRenderIntent.assetValue, rawHncsFilmCurveMode = metadata.rawHncsFilmCurveMode.persistedValue, rawColorEngine = metadata.rawRenderingEngine.name, + rawOutputUpscaleMode = metadata.rawOutputUpscaleMode.name, rawAgxBlackRelativeExposure = metadata.rawToneMappingParameters.agxBlackRelativeExposure, rawAgxWhiteRelativeExposure = metadata.rawToneMappingParameters.agxWhiteRelativeExposure, rawAgxToe = metadata.rawToneMappingParameters.agxToe, @@ -451,6 +453,7 @@ object GalleryMediaStore { rawColorEngine, fallback = RawRenderingEngine.AdobeCurve ), + rawOutputUpscaleMode = RawOutputUpscaleMode.fromName(rawOutputUpscaleMode), rawToneMappingParameters = RawToneMappingParameters( agxBlackRelativeExposure = rawAgxBlackRelativeExposure, agxWhiteRelativeExposure = rawAgxWhiteRelativeExposure, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/MgcRaisrUpscale.kt b/app/src/main/java/com/hinnka/mycamera/raw/MgcRaisrUpscale.kt new file mode 100644 index 00000000..7c94775d --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/MgcRaisrUpscale.kt @@ -0,0 +1,145 @@ +package com.hinnka.mycamera.raw + +import android.graphics.Bitmap +import android.graphics.Matrix +import com.hinnka.mycamera.utils.PLog +import java.nio.ByteBuffer + +/** + * Kotlin face of the lifted MGC V25 RAISR finish-stage upscale. + * + * The chain is five AOT kernels lifted byte-identically from the pinned + * `libgcastartup.so` (RGB to grey, orientation, filter-class hash, 2x per-shift + * filtering and the artifact composite); the npcam glue around them is rebuilt + * in `mgc_raisr_driver.cpp`, and `mgc_raisr_jni.cpp` drives it over Photon's own + * containers. Everything runs in the UInt8 finish domain, which the on-device + * probe confirmed kernel by kernel. + * + * The upscale itself - the band loop, its scratch budget, the half-float and + * ARGB_8888 to float conversion, the float to ARGB_8888 conversion - is native + * and bounded by a fixed budget rather than by the frame size, so nothing here + * sizes a buffer or walks a pixel. This class only owns the two bitmaps that are + * the frame the caller already holds and the image it asked for. + * + * [upscale] consumes the finalized image at its native grid and produces the 2x + * image, so it is the RAISR counterpart of the Lanczos-3 magnification in + * [RawOutputPass] and the two are never combined. + */ +internal class MgcRaisrUpscale { + /** V25's RaisrUpsample pins the integer factor; only 2x is reachable here. */ + val scale = 2 + + /** + * Upscales a finalized frame. + * + * The caller may pass the frame in any bitmap format the chain can read + * (RGBA_F16 as the GPU hands it back, or ARGB_8888); the native side owns + * that conversion too. `source` stays untouched. + */ + fun upscale(source: Bitmap): Bitmap? { + val width = source.width + val height = source.height + if (width <= 0 || height <= 0) { + return null + } + val output = createOutput(width * scale, height * scale) ?: return null + val status = nativeUpscaleBitmap(source, output) + if (status != 0) { + PLog.e(TAG, "MGC RAISR upscale failed status=$status input=${width}x$height") + output.recycle() + return null + } + return output + } + + /** + * Upscales one tile of a tiled render. + * + * [buffer] holds the whole working tile at native scale in its own (source) + * orientation, and the core occupies `coreLeft/coreTop/coreWidth/coreHeight` + * inside it. The native side feeds the chain the core plus the halo its 5x5 + * window needs and crops the margin from the 2x result again, so the tile + * scratch stays inside the same budget as the whole-frame path. The caller + * rotates the result into output orientation. + */ + fun upscaleTile( + buffer: ByteBuffer, + tileWidth: Int, + tileHeight: Int, + coreLeft: Int, + coreTop: Int, + coreWidth: Int, + coreHeight: Int, + ): Bitmap? { + if (tileWidth <= 0 || tileHeight <= 0 || coreWidth <= 0 || coreHeight <= 0) { + return null + } + val output = createOutput(coreWidth * scale, coreHeight * scale) ?: return null + val status = nativeUpscaleTile( + buffer, + tileWidth, + tileHeight, + coreLeft, + coreTop, + coreWidth, + coreHeight, + output, + ) + if (status != 0) { + PLog.e( + TAG, + "MGC RAISR tile upscale failed status=$status core=${coreWidth}x$coreHeight", + ) + output.recycle() + return null + } + return output + } + + /** Rotates a source-orientation result into the output orientation. */ + fun rotateForOutput(source: Bitmap, rotation: Int): Bitmap { + val normalized = ((rotation % 360) + 360) % 360 + if (normalized == 0) { + return source + } + val matrix = Matrix().apply { postRotate(normalized.toFloat()) } + return Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true) + } + + /** + * The 2x image the caller asked for, filled in place by the native chain. + * + * Android bitmaps hold their pixels on the native heap, and the native side + * locks this one, so no buffer of this size ever crosses the JNI boundary. + * `Bitmap.createBitmap(width, height, config)` is the mutable overload the + * lock requires. + */ + private fun createOutput(width: Int, height: Int): Bitmap? = + try { + Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) + } catch (ignored: OutOfMemoryError) { + PLog.e(TAG, "MGC RAISR refused a ${width}x$height output bitmap") + null + } + + private external fun nativeUpscaleBitmap(source: Bitmap, destination: Bitmap): Int + + private external fun nativeUpscaleTile( + source: ByteBuffer, + tileWidth: Int, + tileHeight: Int, + coreLeft: Int, + coreTop: Int, + coreWidth: Int, + coreHeight: Int, + destination: Bitmap, + ): Int + + companion object { + private const val TAG = "MgcRaisrUpscale" + + init { + System.loadLibrary("my-native-lib") + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt index 615838cb..19b1456b 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt @@ -1411,6 +1411,10 @@ class RawDemosaicProcessor { private val sharpenPass = RawSharpenPass(fullscreenQuad) private val mgcSharpen = MgcSharpen() private val denoiseTransfer = RawFloatTextureTransfer(RawFloatTextureTransfer.Layout.HALF) + /** RAISR reads the finalized tile as float RGBA, so it needs its own transfer layout. */ + private val raisrTransfer = RawFloatTextureTransfer(RawFloatTextureTransfer.Layout.FLOAT) + /** Lifted MGC RAISR finish-stage magnification; only used at the 2x output scale. */ + private val mgcRaisrUpscale = MgcRaisrUpscale() private val outputPass = RawOutputPass(fullscreenQuad) private val linearUintToFloatPass = RawLinearUintToFloatPass() private val linearRgbExpandPass = RawLinearRgbExpandPass() @@ -1754,6 +1758,7 @@ class RawDemosaicProcessor { rawCfaCorrectionMode: String? = null, rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(), rawOutputScale: Float = 1f, + rawOutputUpscaleMode: RawOutputUpscaleMode = RawOutputUpscaleMode.DEFAULT, rawPhysicalOutputSize: Size? = null, onMetadata: ((RawMetadata) -> Unit)? = null ): Bitmap? = withContext(glDispatcher) { @@ -1805,6 +1810,7 @@ class RawDemosaicProcessor { rawCfaCorrectionMode = rawCfaCorrectionMode, rawBlackBorderCrop = rawBlackBorderCrop, rawOutputScale = rawOutputScale, + rawOutputUpscaleMode = rawOutputUpscaleMode, rawPhysicalOutputSize = rawPhysicalOutputSize, dngFile = dngFile, onMetadata = onMetadata @@ -1853,6 +1859,7 @@ class RawDemosaicProcessor { rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT, rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(), rawOutputScale: Float = 1f, + rawOutputUpscaleMode: RawOutputUpscaleMode = RawOutputUpscaleMode.DEFAULT, rawPhysicalOutputSize: Size? = null, ): Bitmap? = withContext(glDispatcher) { try { @@ -1898,6 +1905,7 @@ class RawDemosaicProcessor { rawToneMappingParameters = rawToneMappingParameters, rawBlackBorderCrop = rawBlackBorderCrop, rawOutputScale = rawOutputScale, + rawOutputUpscaleMode = rawOutputUpscaleMode, rawPhysicalOutputSize = rawPhysicalOutputSize, )?.sdrBitmap } catch (e: Exception) { @@ -2006,6 +2014,7 @@ class RawDemosaicProcessor { rawCfaCorrectionMode: String? = null, rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(), rawOutputScale: Float = 1f, + rawOutputUpscaleMode: RawOutputUpscaleMode = RawOutputUpscaleMode.DEFAULT, rawPhysicalOutputSize: Size? = null, includeHdrReference: Boolean, photonHdrRatio: Float? = null, @@ -2059,6 +2068,7 @@ class RawDemosaicProcessor { rawCfaCorrectionMode = rawCfaCorrectionMode, rawBlackBorderCrop = rawBlackBorderCrop, rawOutputScale = rawOutputScale, + rawOutputUpscaleMode = rawOutputUpscaleMode, rawPhysicalOutputSize = rawPhysicalOutputSize, dngFile = dngFile, onMetadata = onMetadata, @@ -2124,6 +2134,7 @@ class RawDemosaicProcessor { rawCfaCorrectionMode: String? = null, rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(), rawOutputScale: Float = 1f, + rawOutputUpscaleMode: RawOutputUpscaleMode = RawOutputUpscaleMode.DEFAULT, rawPhysicalOutputSize: Size? = null, includeHdrReference: Boolean, photonHdrRatio: Float? = null, @@ -2223,6 +2234,7 @@ class RawDemosaicProcessor { rawCfaCorrectionMode = rawCfaCorrectionMode, rawBlackBorderCrop = rawBlackBorderCrop, rawOutputScale = rawOutputScale, + rawOutputUpscaleMode = rawOutputUpscaleMode, rawPhysicalOutputSize = rawPhysicalOutputSize, includeHdrReference = includeHdrReference, sourceDngRenderPlan = embeddedDngRenderPlan, @@ -2293,6 +2305,7 @@ class RawDemosaicProcessor { rawCfaCorrectionMode: String? = null, rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(), rawOutputScale: Float = 1f, + rawOutputUpscaleMode: RawOutputUpscaleMode = RawOutputUpscaleMode.DEFAULT, rawPhysicalOutputSize: Size? = null, dngFile: File? = null, onMetadata: ((RawMetadata) -> Unit)? = null, @@ -2695,13 +2708,15 @@ class RawDemosaicProcessor { actualRotation, rawOutputScale, referenceWidth = physicalOutputBounds?.width() ?: outputSourceBounds.width(), referenceHeight = physicalOutputBounds?.height() ?: outputSourceBounds.height(), + upscaleMode = rawOutputUpscaleMode, ) PLog.i( TAG, "RAW_OUTPUT_RESAMPLING source=${outputSourceBounds.width()}x${outputSourceBounds.height()} " + "physicalSize=$rawPhysicalOutputSize scale=$rawOutputScale " + "output=${outputGeometry.width}x${outputGeometry.height} " + - "lanczos=${outputGeometry.resample}", + "lanczos=${outputGeometry.resample} " + + "upscale=${rawOutputUpscaleMode.name} raisr=${outputGeometry.raisrUpsample}", ) val rawOutputBounds = outputSourceBounds.toOutputBounds(actualRotation) val applicableDngWarpRectilinear = filterApplicableWarpRectilinear( @@ -4064,6 +4079,14 @@ class RawDemosaicProcessor { // 7. 第四步:输出旋转 (Output Pass) setupOutputFramebuffer(finalWidth, finalHeight) + // MGC RAISR magnifies on its own, so this path finalizes the frame on + // its native grid and lifts it in one RAISR step instead of letting + // RawOutputPass resample it with Lanczos-3. + val raisrNativeGeometry = if (outputGeometry.raisrUpsample) { + outputGeometry.nativeGrid() + } else { + null + } val outputStart = System.currentTimeMillis() renderOutputPass( actualRotation, @@ -4071,12 +4094,15 @@ class RawDemosaicProcessor { actualHeight, bounds, sourceTextureForOutput, - geometry = outputGeometry, + geometry = raisrNativeGeometry ?: outputGeometry, ) PLog.d(TAG, "Output Pass took: ${System.currentTimeMillis() - outputStart}ms") // HDR must use this exact finalized SDR color as well. Keep it through HDR output; // processInternal's finally releases it on success, failure, or cancellation. - if (!includeHdrReference) releaseSharpenFramebuffer() + // The RAISR branch below holds it one step longer: a refused upscale re-renders + // this same finalized texture on the Lanczos-3 grid, so it may only be released + // once the lifted chain has actually produced the frame. + if (!includeHdrReference && raisrNativeGeometry == null) releaseSharpenFramebuffer() // 8. 读取结果。先单独等待 GPU,避免把前面所有异步 shader 工作记到 readPixels。 val upstreamStackTiming = borrowedGpuSource?.stackCompletionTimeline?.awaitPending( @@ -4088,7 +4114,49 @@ class RawDemosaicProcessor { checkGlError = ::checkGlError, ) val readStart = System.currentTimeMillis() - val finalBitmap = readPixels(finalWidth, finalHeight, workingColorSpace) + var raisrApplied = false + val finalBitmap = if (raisrNativeGeometry != null) { + val nativeBitmap = readPixels( + raisrNativeGeometry.width, + raisrNativeGeometry.height, + workingColorSpace, + ) + val upscaled = nativeBitmap?.let { + try { + mgcRaisrUpscale.upscale(it) + } finally { + it.recycle() + } + } + raisrApplied = upscaled != null + if (upscaled != null) { + if (!includeHdrReference) releaseSharpenFramebuffer() + upscaled + } else { + // The lifted chain can refuse a frame - no band scratch, or a + // driver status - and the shot still has to complete. Reset + // the output pass to the Lanczos-3 grid, exactly as when + // RAISR is not the selected algorithm at all. + PLog.w( + TAG, + "MGC RAISR unavailable for the untiled ${raisrNativeGeometry.width}x" + + "${raisrNativeGeometry.height} output; using Lanczos-3", + ) + renderOutputPass( + actualRotation, + actualWidth, + actualHeight, + bounds, + sourceTextureForOutput, + geometry = outputGeometry, + ) + val fallback = readPixels(finalWidth, finalHeight, workingColorSpace) + if (!includeHdrReference) releaseSharpenFramebuffer() + fallback + } + } else { + readPixels(finalWidth, finalHeight, workingColorSpace) + } val outputMaterializationMs = System.currentTimeMillis() - readStart PLog.d( TAG, @@ -4135,6 +4203,17 @@ class RawDemosaicProcessor { applyDcpHueSatMap = deferDcpHueSatUntilAfterPgtm, ) } + if (raisrApplied) { + // The HDR gain reference is resampled on the GPU from the + // finalized texture, so it cannot consume the CPU RAISR + // result; it stays on the Lanczos-3 grid while the SDR + // base is magnified by RAISR. + PLog.w( + TAG, + "MGC RAISR is active; the Ultra HDR gain reference keeps " + + "Lanczos-3 resampling while the SDR base uses RAISR", + ) + } renderOutputPass( actualRotation, actualWidth, @@ -4548,6 +4627,75 @@ class RawDemosaicProcessor { hdrTileBitmap.recycle() } } + // MGC RAISR magnifies the tile itself. The working texture is in + // source orientation, so the core is read back in source-local + // coordinates and upscaled; the native chain adds the halo its + // 5x5 window needs inside the tile and crops it again, then the + // caller rotates the result into output orientation. + val raisrTile: Bitmap? = if (config.outputGeometry.raisrUpsample) { + var upscaledTile: Bitmap? = null + raisrTransfer.read( + texture = sharpenTextureId, + width = workWidth, + height = workHeight, + capacityPixels = workWidth.toLong() * workHeight, + label = "raisrTile", + ) { rgba -> + upscaledTile = mgcRaisrUpscale.upscaleTile( + buffer = rgba, + tileWidth = workWidth, + tileHeight = workHeight, + coreLeft = localSourceCore.left, + coreTop = localSourceCore.top, + coreWidth = localSourceCore.width(), + coreHeight = localSourceCore.height(), + ) + } + val nativeTile = upscaledTile + if (nativeTile == null) { + PLog.e(TAG, "MGC RAISR produced no tile for ${localSourceCore}") + null + } else { + val orientedTile = + mgcRaisrUpscale.rotateForOutput(nativeTile, config.rotation) + if (orientedTile !== nativeTile) { + nativeTile.recycle() + } + // RAISR magnifies by exactly 2x, so the tile must land on + // its scaled core. With RAW digital-zoom resampling the + // 1x grid is the physical output size and the core is not + // exactly doubled; drawing it anyway would misplace pixels, + // so this tile falls back to Lanczos-3 instead. + if (orientedTile.width != scaledCore.width || + orientedTile.height != scaledCore.height + ) { + PLog.e( + TAG, + "MGC RAISR tile is ${orientedTile.width}x${orientedTile.height} " + + "but its scaled core is ${scaledCore.width}x${scaledCore.height}; " + + "this tile falls back to Lanczos-3", + ) + orientedTile.recycle() + null + } else { + orientedTile + } + } + } else { + null + } + if (raisrTile != null) { + try { + sdrCanvas.drawBitmap( + raisrTile, + scaledCore.left.toFloat(), + scaledCore.top.toFloat(), + copyPaint, + ) + } finally { + raisrTile.recycle() + } + } else { renderOutputPass( rotation = config.rotation, width = workWidth, @@ -4574,11 +4722,14 @@ class RawDemosaicProcessor { } finally { tileBitmap.recycle() } + } GlesGpuScheduler.waitForGpuCheckpoint(TAG, "RAW tile ${tile.index + 1}") PLog.d( TAG, "RAW_TILE_DONE index=${tile.index + 1}/${config.tiles.size} " + "output=${tile.outputCore} source=${tile.sourceCore} work=$working " + + "scaled=$scaledCore localCore=$localSourceCore " + + "upscale=${if (config.outputGeometry.raisrUpsample) "raisr" else "lanczos"} " + "tookMs=${(System.nanoTime() - tileStartNs) / 1_000_000}", ) } @@ -4722,6 +4873,7 @@ class RawDemosaicProcessor { private fun releaseTiledRenderFramebuffers() { mgcSharpen.releaseBuffers() + raisrTransfer.releaseBuffers() vgnDemosaicAlgorithm.setTileTexturePoolingEnabled(false) if (rawTextureId != 0) { GLES30.glDeleteTextures(1, intArrayOf(rawTextureId), 0) @@ -9097,6 +9249,7 @@ class RawDemosaicProcessor { sharpenPass.release() mgcSharpen.release() denoiseTransfer.release() + raisrTransfer.release() outputPass.release() hdrReferencePass.release() chromaDenoiseAlgorithm.release() diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawOutputGeometry.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawOutputGeometry.kt index 1d90f918..630b5074 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawOutputGeometry.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawOutputGeometry.kt @@ -8,8 +8,12 @@ internal class RawOutputGeometry( val sourceBounds: RawTileRect, val rotation: Int, scale: Float, - referenceWidth: Int = sourceBounds.width, - referenceHeight: Int = sourceBounds.height, + // Both references are in the unrotated frame, exactly like a physical output + // size; the constructor swaps them for 90/270. Passing the already-rotated + // native dimensions here transposes the grid. + private val referenceWidth: Int = sourceBounds.width, + private val referenceHeight: Int = sourceBounds.height, + val upscaleMode: RawOutputUpscaleMode = RawOutputUpscaleMode.DEFAULT, ) { init { require(rotation in setOf(0, 90, 180, 270)) @@ -19,12 +23,28 @@ internal class RawOutputGeometry( private val nativeHeight = if (rotation % 180 == 0) sourceBounds.height else sourceBounds.width private val outputBaseWidth = if (rotation % 180 == 0) referenceWidth else referenceHeight private val outputBaseHeight = if (rotation % 180 == 0) referenceHeight else referenceWidth - val width = MultiFrameConfig.scaledRawOutputDimension(outputBaseWidth, scale) - val height = MultiFrameConfig.scaledRawOutputDimension(outputBaseHeight, scale) + /** RAISR pins its own per-shift magnification, so the mode owns the effective scale. */ + val outputScale = upscaleMode.resolveOutputScale(scale) + val width = MultiFrameConfig.scaledRawOutputDimension(outputBaseWidth, outputScale) + val height = MultiFrameConfig.scaledRawOutputDimension(outputBaseHeight, outputScale) val mgcFinishResolution = MgcFinishResolution.resolve(nativeWidth, nativeHeight, width, height) val resample = width != nativeWidth || height != nativeHeight + /** MGC RAISR replaces the Lanczos-3 resample whenever both are eligible. */ + val raisrUpsample = upscaleMode.usesRaisr(outputScale) && resample val fullRegion = RawTileRect(0, 0, width, height) + /** + * The same crop, rotation and reference grid at 1x, i.e. the grid MGC RAISR + * consumes before it magnifies the image itself. + * + * The reference must be carried over: with RAW digital-zoom resampling the + * 1x grid is the physical output size, not the crop size, and dropping it + * renders the capture on the wrong grid (a portrait burst comes out as a + * squashed landscape). + */ + fun nativeGrid(): RawOutputGeometry = + RawOutputGeometry(sourceBounds, rotation, 1f, referenceWidth, referenceHeight) + /** Round shared edges once on the global grid, never resize each tile independently. */ fun scaleRegion(region: RawTileRect) = RawTileRect( (region.left.toDouble() * width / nativeWidth).roundToInt(), @@ -68,10 +88,27 @@ internal class RawOutputGeometry( /** Stored separately from native DNG dimensions; older already-scaled DNGs default to 1x. */ object RawOutputScaling { private const val KEY = "rawDisplayOutputScale" + private const val MODE_KEY = "rawDisplayOutputUpscaleMode" - fun read(properties: Map): Float = - MultiFrameConfig.normalizeOutputScale(properties[KEY]?.toFloatOrNull() ?: 1f) + fun read(properties: Map): Float { + val requested = MultiFrameConfig.normalizeOutputScale( + properties[KEY]?.toFloatOrNull() ?: 1f, + ) + return readUpscaleMode(properties).resolveOutputScale(requested) + } - fun write(properties: Map, scale: Float): Map = - properties + (KEY to MultiFrameConfig.normalizeOutputScale(scale).toString()) + /** Absent on photos captured before the algorithm setting existed; those used Lanczos-3. */ + fun readUpscaleMode(properties: Map): RawOutputUpscaleMode = + RawOutputUpscaleMode.fromName(properties[MODE_KEY]) + + fun write( + properties: Map, + scale: Float, + upscaleMode: RawOutputUpscaleMode = RawOutputUpscaleMode.DEFAULT, + ): Map { + val mode = if (upscaleMode.isMgcRaisr) upscaleMode else RawOutputUpscaleMode.DEFAULT + return properties + + (KEY to mode.resolveOutputScale(scale).toString()) + + (MODE_KEY to mode.name) + } } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawOutputUpscaleMode.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawOutputUpscaleMode.kt new file mode 100644 index 00000000..ebfbe581 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawOutputUpscaleMode.kt @@ -0,0 +1,43 @@ +package com.hinnka.mycamera.raw + +import com.hinnka.mycamera.camera.MultiFrameConfig + +/** + * Professional-mode output magnification algorithm. + * + * MGC V25's finish upsamplers are two mutually exclusive implementations: `LancetUpsample` + * (Lanczos) and `RaisrUpsample` (RAISR). RAISR's per-shift 5x5 filtering only accepts integer + * scale factors of 2x/3x/4x and its stage rejects a resample rate below 2.0, so within Photon's + * 1x..2x output scale range it is only reachable at exactly 2x. Selecting RAISR therefore pins + * the output scale; Lanczos-3 keeps the whole continuous range. + */ +enum class RawOutputUpscaleMode { + LANCZOS3, + MGC_RAISR; + + val isMgcRaisr: Boolean + get() = this == MGC_RAISR + + /** Scale this mode is pinned to, or null when the caller keeps its own scale. */ + val pinnedOutputScale: Float? + get() = if (this == MGC_RAISR) RAISR_REQUIRED_OUTPUT_SCALE else null + + /** Effective output scale for this algorithm. */ + fun resolveOutputScale(requestedScale: Float): Float = + pinnedOutputScale ?: MultiFrameConfig.normalizeOutputScale(requestedScale) + + /** RAISR replaces the Lanczos resample only when its pinned scale is actually reached. */ + fun usesRaisr(requestedScale: Float): Boolean = + this == MGC_RAISR && + MultiFrameConfig.normalizeOutputScale(requestedScale) == RAISR_REQUIRED_OUTPUT_SCALE + + companion object { + val DEFAULT: RawOutputUpscaleMode = LANCZOS3 + + /** `RaisrUpsample` requires `resample_rate >= 2.0`; the output scale ceiling is 2x. */ + const val RAISR_REQUIRED_OUTPUT_SCALE = 2f + + fun fromName(name: String?): RawOutputUpscaleMode = + entries.firstOrNull { it.name == name } ?: DEFAULT + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt index c6ed8b63..930620d6 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt @@ -96,6 +96,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.hinnka.mycamera.processor.DenoiseStrength import com.hinnka.mycamera.processor.MgcRawMaxMode +import com.hinnka.mycamera.raw.RawOutputUpscaleMode import androidx.core.net.toUri import androidx.core.os.LocaleListCompat import androidx.lifecycle.Lifecycle @@ -412,6 +413,7 @@ fun SettingsScreen( val rawSpectralFilmSelection by viewModel.rawSpectralFilmSelection.collectAsState() val rawSpectralFilmPrint by viewModel.rawSpectralFilmPrint.collectAsState() val rawMaxOutputScale by viewModel.rawMaxOutputScale.collectAsState() + val rawOutputUpscaleMode by viewModel.rawOutputUpscaleMode.collectAsState() val rawDigitalZoomResamplingEnabled by viewModel.rawDigitalZoomResamplingEnabled.collectAsState() val availableDcps = viewModel.availableDcps val availableRawNoiseProfiles = viewModel.availableRawNoiseProfiles.filterNot { @@ -2100,11 +2102,38 @@ fun SettingsScreen( modifier = Modifier.padding(vertical = 12.dp) ) + QualityLevelSetting( + title = stringResource(R.string.settings_raw_output_upscale_mode), + description = stringResource( + R.string.settings_raw_output_upscale_mode_description + ), + levels = listOf( + RawOutputUpscaleMode.LANCZOS3 to stringResource( + R.string.settings_raw_output_upscale_mode_lanczos + ), + RawOutputUpscaleMode.MGC_RAISR to stringResource( + R.string.settings_raw_output_upscale_mode_raisr + ), + ), + currentLevel = rawOutputUpscaleMode, + onLevelSelected = viewModel::setRawOutputUpscaleMode, + ) + + HorizontalDivider( + color = Color.White.copy(alpha = 0.1f), + modifier = Modifier.padding(vertical = 12.dp) + ) + val valueFormat = stringResource(R.string.settings_raw_max_output_scale_value) + val raisrUpscaleActive = rawOutputUpscaleMode.isMgcRaisr SliderSettingItem( title = stringResource(R.string.settings_raw_max_output_scale), description = stringResource( - R.string.settings_raw_max_output_scale_description + if (raisrUpscaleActive) { + R.string.settings_raw_max_output_scale_description_raisr + } else { + R.string.settings_raw_max_output_scale_description + } ), value = rawMaxOutputScaleUi, valueRange = MultiFrameConfig.MIN_OUTPUT_SCALE..MultiFrameConfig.MAX_OUTPUT_SCALE, @@ -2119,7 +2148,8 @@ fun SettingsScreen( onValueChangeFinished = { viewModel.setRawMaxOutputScale(rawMaxOutputScaleUi) }, - valueTextFormatter = { scale -> String.format(valueFormat, scale) } + valueTextFormatter = { scale -> String.format(valueFormat, scale) }, + enabled = !raisrUpscaleActive, ) HorizontalDivider( diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index 691f9bb1..75262e00 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -69,6 +69,7 @@ import com.hinnka.mycamera.raw.DcpProfileParser import com.hinnka.mycamera.raw.DcpInfo import com.hinnka.mycamera.raw.HncsFilmCurveMode import com.hinnka.mycamera.raw.HncsRenderIntent +import com.hinnka.mycamera.raw.RawOutputUpscaleMode import com.hinnka.mycamera.raw.HncsProfileManager import com.hinnka.mycamera.color.TransferCurve import com.hinnka.mycamera.model.EffectParams @@ -1726,6 +1727,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) SharingStarted.Eagerly, MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE, ) + val rawOutputUpscaleMode: StateFlow = + userPreferencesRepository.userPreferences + .map { it.rawOutputUpscaleMode } + .stateIn(viewModelScope, SharingStarted.Eagerly, RawOutputUpscaleMode.DEFAULT) val useLivePhoto: StateFlow = userPreferencesRepository.userPreferences .map { it.useLivePhoto } .stateIn(viewModelScope, SharingStarted.Eagerly, false) @@ -3049,6 +3054,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) rawBlackBorderCrop = settings.blackBorderCrop, rawRenderingEngine = resolveCaptureRawRenderingEngine(userPrefs), rawToneMappingParameters = rawToneMappingParameters, + rawOutputUpscaleMode = userPrefs?.rawOutputUpscaleMode ?: RawOutputUpscaleMode.DEFAULT, spectralFilmStock = spectralFilmSettings.stock, spectralFilmPrint = spectralFilmSettings.print, spectralFilmCDensityGain = spectralFilmSettings.tuning.cDensityGain, @@ -4855,12 +4861,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) fun setRawMaxOutputScale(scale: Float) { viewModelScope.launch { - val normalizedScale = MultiFrameConfig.normalizeOutputScale( - outputScale = scale, - fallback = MultiFrameConfig.DEFAULT_SUPER_RESOLUTION_SCALE, - ) - userPreferencesRepository.saveRawMaxOutputScale(normalizedScale) val prefs = userPreferencesRepository.userPreferences.first() + val normalizedScale = prefs.rawOutputUpscaleMode.resolveOutputScale(scale) + userPreferencesRepository.saveRawMaxOutputScale(normalizedScale) cameraController.setMultiFrameOutputScale( resolveMultiFrameOutputScale( useJpgMax = prefs.useJpgMax && !prefs.useRaw && @@ -4874,6 +4877,27 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } } + /** + * 设置 RAWmax 输出放大算法。MGC RAISR 与原版一致只支持 2x per-shift 放大, + * 因此选中时输出倍率由偏好层锁定为 2x,与 Lanczos 连续倍率放大互斥。 + */ + fun setRawOutputUpscaleMode(mode: RawOutputUpscaleMode) { + viewModelScope.launch { + userPreferencesRepository.saveRawOutputUpscaleMode(mode) + val prefs = userPreferencesRepository.userPreferences.first() + cameraController.setMultiFrameOutputScale( + resolveMultiFrameOutputScale( + useJpgMax = prefs.useJpgMax && !prefs.useRaw && + !prefs.useMultipleExposure, + useRawMax = prefs.useRawMax && prefs.useRaw && + !prefs.useMultipleExposure, + rawMaxOutputScale = prefs.rawMaxOutputScale, + jpgMultiFrameDenoiseOutputScale = prefs.jpgMultiFrameDenoiseOutputScale, + ) + ) + } + } + private fun shouldEnableLivePhoto(prefs: UserPreferences): Boolean { // RAWmax supports Live Photo. A saved JPGmax preference is inactive in RAW mode. val activeUseJpgMax = prefs.useJpgMax && !prefs.useRaw @@ -5830,6 +5854,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) rawBlackBorderCrop = settings.blackBorderCrop, rawRenderingEngine = resolveCaptureRawRenderingEngine(userPrefs), rawToneMappingParameters = rawToneMappingParameters, + rawOutputUpscaleMode = userPrefs?.rawOutputUpscaleMode ?: RawOutputUpscaleMode.DEFAULT, spectralFilmStock = spectralFilmSettings.stock, spectralFilmPrint = spectralFilmSettings.print, spectralFilmCDensityGain = spectralFilmSettings.tuning.cDensityGain, @@ -6263,6 +6288,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) rawBlackBorderCrop = settings.blackBorderCrop, rawRenderingEngine = resolveCaptureRawRenderingEngine(userPrefs), rawToneMappingParameters = rawToneMappingParameters, + rawOutputUpscaleMode = userPrefs?.rawOutputUpscaleMode ?: RawOutputUpscaleMode.DEFAULT, spectralFilmStock = spectralFilmSettings.stock, spectralFilmPrint = spectralFilmSettings.print, spectralFilmCDensityGain = spectralFilmSettings.tuning.cDensityGain, @@ -6585,6 +6611,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) rawBlackBorderCrop = settings.blackBorderCrop, rawRenderingEngine = resolveCaptureRawRenderingEngine(userPrefs), rawToneMappingParameters = rawToneMappingParameters, + rawOutputUpscaleMode = userPrefs?.rawOutputUpscaleMode ?: RawOutputUpscaleMode.DEFAULT, spectralFilmStock = spectralFilmSettings.stock, spectralFilmPrint = spectralFilmSettings.print, spectralFilmCDensityGain = spectralFilmSettings.tuning.cDensityGain, diff --git a/app/src/main/res/values-b+zh+Hant/strings.xml b/app/src/main/res/values-b+zh+Hant/strings.xml index 4890b8bd..85988c6c 100644 --- a/app/src/main/res/values-b+zh+Hant/strings.xml +++ b/app/src/main/res/values-b+zh+Hant/strings.xml @@ -267,6 +267,11 @@ HDR+ 輸出倍率 調整 HDR+ 相片的輸出尺寸。倍率越高,相片尺寸和檔案大小越大,處理時間也可能更長。 %1$.2f× + 輸出放大演算法 + 選擇專業模式輸出的放大演算法。MGC RAISR 與 Lanczos-3 倍率放大互斥。 + Lanczos-3 + MGC RAISR + MGC RAISR 僅在 2× 下放大,選取期間輸出倍率固定為 2×。 多幀降噪幀數 照片模式下多幀降噪使用的幀數。幀數越多降噪越明顯,但處理時間也越長。 多幀降噪輸出倍率 diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index d51ddc35..6350c9e9 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -478,6 +478,11 @@ 1枚の最終画像に合成する露光枚数。クラシックな二重露光ではデフォルト2枚です。 HDR+出力スケール HDR+写真の出力サイズを調整します。倍率を上げるほど画像とファイルが大きくなり、処理時間も長くなる場合があります。 + 出力アップスケール + プロフェッショナルモード出力の拡大アルゴリズムを選択します。MGC RAISR と Lanczos-3 の倍率拡大は排他的です。 + Lanczos-3 + MGC RAISR + MGC RAISR は 2× でのみ拡大するため、選択中は出力倍率が 2× に固定されます。 マルチフレームNR枚数 写真モードのマルチフレームNRに使うフレーム数。増やすほどノイズは減りますが、処理時間は長くなります。 マルチフレームNR出力スケール diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 2ac0462e..105345ef 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -931,6 +931,11 @@ โทนแสง ปรับคุณภาพภาพ HDR+ ปรับการประเมินสัญญาณรบกวนในการรวมภาพและการลดสัญญาณรบกวนตามขนาดจริงของเซ็นเซอร์ เมื่อปิดจะใช้พารามิเตอร์ภาพเริ่มต้น + อัลกอริทึมการขยายเอาต์พุต + เลือกอัลกอริทึมที่ใช้ขยายเอาต์พุตในโหมดโปรเฟสชันนัล MGC RAISR และการขยายด้วย Lanczos-3 ใช้พร้อมกันไม่ได้ + Lanczos-3 + MGC RAISR + MGC RAISR ขยายได้ที่ 2× เท่านั้น ระหว่างที่เลือกไว้ อัตราขยายเอาต์พุตจะถูกล็อกไว้ที่ 2× เสียงถ่ายภาพเดี่ยว เสียงถ่ายภาพต่อเนื่อง นำเข้าคลิปเสียงความยาวไม่เกิน 3 วินาที, 48 kHz, โมโนหรือสเตอริโอ เสียงถ่ายภาพต่อเนื่องจะเล่นซ้ำขณะถ่ายภาพ diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 47b1ec28..d16527e9 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -268,6 +268,11 @@ HDR+ 输出倍率 调整 HDR+ 照片的输出尺寸。倍率越高,照片尺寸和文件体积越大,处理时间也可能更长。 %1$.2f× + 输出放大算法 + 选择专业模式输出的放大算法。MGC RAISR 与 Lanczos-3 倍率放大互斥。 + Lanczos-3 + MGC RAISR + MGC RAISR 仅在 2× 下放大,选中期间输出倍率固定为 2×。 多帧降噪帧数 照片模式下多帧降噪使用的帧数。帧数越多降噪越明显,但处理时间也越长。 多帧降噪输出倍率 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 1fc7f4ef..8f3c333e 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -267,6 +267,11 @@ HDR+ 輸出倍率 調整 HDR+ 相片的輸出尺寸。倍率越高,相片尺寸和檔案大小越大,處理時間也可能更長。 %1$.2f× + 輸出放大演算法 + 選擇專業模式輸出的放大演算法。MGC RAISR 與 Lanczos-3 倍率放大互斥。 + Lanczos-3 + MGC RAISR + MGC RAISR 僅在 2× 下放大,選取期間輸出倍率固定為 2×。 多幀降噪幀數 照片模式下多幀降噪使用的幀數。幀數越多降噪越明顯,但處理時間也越長。 多幀降噪輸出倍率 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index b366d334..88066164 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -267,6 +267,11 @@ HDR+ 輸出倍率 調整 HDR+ 相片的輸出尺寸。倍率越高,相片尺寸和檔案大小越大,處理時間也可能更長。 %1$.2f× + 輸出放大演算法 + 選擇專業模式輸出的放大演算法。MGC RAISR 與 Lanczos-3 倍率放大互斥。 + Lanczos-3 + MGC RAISR + MGC RAISR 僅在 2× 下放大,選取期間輸出倍率固定為 2×。 多幀降噪幀數 照片模式下多幀降噪使用的幀數。幀數越多降噪越明顯,但處理時間也越長。 多幀降噪輸出倍率 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 980aff22..4f277037 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -278,6 +278,11 @@ HDR+ output scale Adjusts the size of HDR+ photos. A higher scale produces larger photos and files, and may take longer to process. %1$.2f× + Output upscaling + Selects the algorithm that magnifies the professional-mode output. MGC RAISR and Lanczos-3 magnification are mutually exclusive. + Lanczos-3 + MGC RAISR + MGC RAISR magnifies only at 2×, so the output scale is fixed while it is selected. Multi-frame denoise frames Number of frames used for multi-frame denoising in Photo mode. More frames reduce noise further but take longer to process. Multi-frame denoise output scale diff --git a/docs/research/mgc-raisr-driver-spec.md b/docs/research/mgc-raisr-driver-spec.md new file mode 100644 index 00000000..b4cb0a3a --- /dev/null +++ b/docs/research/mgc-raisr-driver-spec.md @@ -0,0 +1,620 @@ +# MGC 9.7.047 V25 RAISR 驱动胶水(npcam/C++ 侧)算法规格 + +本文只覆盖 **AOT 内核之外的胶水层**:`RaisrUpsample` 阶段、compiled-params、滤波器组、 +哈希接口、composite 输入、调用顺序与尺寸。三个 AOT 内核本体(2x per-shift 5x5 滤波、 +hash/filter-class、composite)由他人另行 lift,本文只写它们的**接口契约**。 + +## 0. 二进制与取证方式 + +- 目标:`.codex-tmp/mgc_v25/apk/lib/arm64-v8a/libgcastartup.so` +- SHA-256:`76966e7c150dfcb2795ea5b2119827a7e90b13d8c03035dbc4de583d9d12eaa6`(本次已重新校验(verified)) +- 段映射(`llvm-readelf -l`(verified)): + - `.rodata` VA == 文件偏移 + - `.data` 所属 LOAD 段 `Offset=0x61f9ec0 VirtAddr=0x61fdec0` ⇒ **`.data` 文件偏移 = VA − 0x4000** + (用 `R_AARCH64_RELATIVE` 槽位交叉验证:`.data` 内 4944 个指向 `.rodata` 的 RELATIVE 槽, + 在 VA−0x4000 处全为 0(与"重定位槽在文件中置 0、addend 存 `.rela.dyn`"一致)(verified)) + - 与 `llvm-objdump -s -j .data` 的 VA 行号交叉一致(verified) +- 反汇编:`/opt/homebrew/opt/llvm/bin/llvm-objdump -d --arch-name=aarch64 --start-address=X --stop-address=Y` +- 函数边界来自 `.codex-tmp/ida/mgc_v25/raisr_recon/fde_ranges.txt`(`start size end`) +- 本次新增的原始转储(scratch,未入构建): + `.codex-tmp/ida/mgc_v25/raisr_recon/spec/{xref.py,355f230.txt,355ffec.txt,3589540_3589BF0.txt,` + `0x358f370_0x358f794.txt,0x35a1b24_0x35a27f8.txt,composite.txt,hash2x.txt,2xkernel.txt,` + `3589300_35894AC.txt,data_hexdump.txt,relocs.txt}` +- 本文档标记规则:仅当有指令/字符串/原始字节直接支撑时写 **(verified)**;由多处证据推出但 + 非直接观察写 **(inferred)**;无法静态判定写 **未决**(附具体原因)。 + +### 关键内核名表(`.rodata`,名字串地址(verified)) + +| 名称串地址 | 名称 | 入口(本表新确认的绑定见正文) | +| --- | --- | --- | +| `0xBB5E80` | `NanoRaisrUpscalePerShiftFRH2xInt16Opt5x5Halide` | `0x358A240` | +| `0xBB6340` | `NanoRaisrUpscalePerShiftFRH3xInt16Opt5x5Halide` | `0x358BEF0` | +| `0xBB6800` | `NanoRaisrUpscalePerShiftFRH4xInt16Opt5x5Halide` | `0x358DC94` | +| `0xBB6CC0` | `HashFromOrientation2xThinOptHalide` | `0x3591F3C` | +| `0xBB7000` | `HashFromOrientation3xThinOptHalide` | `0x3596470` | +| `0xBB7340` | `HashFromOrientation4xThinOptHalide` | `0x359A41C` | +| `0xBB7620` | `OrientationUint8ThinOptHalide` | `0x359DAF4` | +| `0xBB7900` | `CensusHighFreqBlenderHalide` | 相邻阶段(本次不展开) | +| `0xBB7C40` | `SharpenDOGHalide` | 相邻阶段(本次不展开) | +| `0xBB8000` | `CopyImageHalide` | `0x35BC4C0` **(inferred)** | +| `0xBB82E0` | `NanoRaisrCompositeHalide` | `0x35C8C54`(由 `0x35A1F70` 调用(verified)) | + +> 更正前一版文档的一处判断:`0x358F794` **不是**独立的 cheap-upscale 内核,它是 +> `HashFromOrientation*` 的 `halide_do_par_for` 体:hash 内核在 `0x35928D8` +> `ldr x1, [x1, #0x80]`(`x1 = GOT[0x61E7080]`)取函数指针,而 `.rela.dyn` 中 +> `r_offset=0x61E7080 → addend=0x358F794`(verified)。 + +--- + +## 1. RAISR upsample 的完整数据流、域、位深与尺寸/对齐 + +### 1.1 入口与前置检查 + +`RaisrUpsample` 阶段入口 **`0x355F230`**(FDE `0x355F230..0x355FFEC`,size `0xDBC`)。 +该函数在整份 `.text` 中只有一个调用者:`0x3364BC8`(位于 `0x33641DC..0x3365320`) +(verified,`bl` 全量扫描)。因此"RAISR 结果如何与色度合成"发生在 `0x33641DC` 内, +本次未展开(见未决事项 §8)。 + +入参(verified): + +- `x0` = 源图像描述符;`float` 域取 `[x0+0x10]` 与 `[x0+0x28]` + (`0x355F2A4 ldr x8,[x21,#0x10]`、`0x355F2B8 ldr x8,[x21,#0x28]`; + `scvtf s1, x8` ⇒ 这两个字段被当作**像素数**,即源宽/高) +- `x1` = user_context(`0x355F40C str x23, [x0]`,写入 `0x427D2F0` 返回的 TLS 槽) +- `x2` = 打包尺寸:低 32 位 = 目标宽,高 32 位 = 目标高 + (`0x355F29C lsr x19, x2, #32`;`0x355F2A8 scvtf s0, w25`(低半)) +- `x3` = 调试/统计相关(`0x355F400 str x26, [sp,#0x58]`,后续只用于可选的 trace 对象) + +```asm +355f2c4: fdiv s0, s0, s1 ; s0 = 目标宽 / 源宽 +355f2d4: fdiv s1, s1, s2 ; s1 = 目标高 / 源高 +355f2d8: fcmp s0, s1 +355f2dc: fcsel s8, s1, s0, mi ; s8 = min(rx, ry) +355f2e0: fmov s0, #2.0 +355f2e4: fcmp s8, s0 +355f2e8: b.pl 0x355f400 ; s8 >= 2.0 才跳过报错 +355f2f4: ... 0x604392 "Upsample: RaisrUpsample expects a resample_rate >= %f but was %f" +``` + +- **`resample_rate = min(target_w/src_w, target_h/src_h)`,要求 ≥ 2.0**(verified)。 + 不满足时只打日志(`__android_log_write(6, "libgcam", ...)`,`0x355F38C..0x355F3B0`)后继续。 + +### 1.2 cheap 输入:luma 由 RGB→Gray Halide 内核产生 + +- `0x355F554 bl 0x3C4E098`:`0x3C4E098` 把 `sp+0x2F8` 的 TImage 包成 Halide buffer 后 + 调用 `0x3C50CBC`(`0x3C4E150 bl 0x3C4E1F0` 建 buffer,`0x3C4E164 bl 0x3C50CBC`)。 +- `0x3C50CBC` 引用的字符串为 `0xC32640 "Output buffer result"`、 + `0xC32660 "Input buffer rgbx_in_"`、`0xC326C0 "rgbx_in_.stride.0"`, + 而内核名 `0xC32620 "RgbToGray3ChOptHalideU8"` 紧邻其前(verified) + ⇒ **RAISR 的输入亮度由 `RgbToGray3ChOptHalideU8`(`0x3C50CBC`) 从 3 通道 RGB 生成**。 +- 结合 `0x58BF21` 的源码级调用串 + `NanoRaisrDirectUpscaleAndRefineLumaMin( *input_y_npcam, cheap_upscaled_y_npcam.get(), compiled_params, nano_raisr_filters, sharpen_params, raisr_rescale_factor, disable_sharpening_and_blending_pass, raisr_upscaled_y_npcam)` + (`0x355FF40` 的 `adrp x3,0x58b000; add x3,x3,#0xf21`(verified))可知: + 进入 RAISR 的是**亮度域**,且源码层面存在"低分辨率 luma"与"cheap upscale 后的 luma"两个图像。 + +### 1.3 两个 npcam 缓冲 / 0x68 字节分配 + +```asm +355f410: mov w0, #0x68 +355f414: ldr x9, [x21, #0x28] ; 源高 +355f41c: ldr x8, [x21, #0x10] ; 源宽 +355f420: lsl x20, x9, #1 ; 2*源高 +355f424: lsl x19, x8, #1 ; 2*源宽 +355f428: bl 0x604e104 ; operator new(0x68) -> x24 +355f444: stp x19, x8, [x24, #0x28] +355f448: stp x20, x8, [x24, #0x40] +``` +之后(`0x355F4D8`)又取 `x19=[x21+0x10]`、`x20=[x21+0x28]`(未乘 2)另建 `x25` +(`0x355F504 stp x19,x8,[x25,#0x28]`、`0x355F508 stp x20,x8,[x25,#0x40]`)。 +- `x24` = 2×源尺寸 的缓冲描述符,`x25` = 1×源尺寸(verified)。 +- 这些 0x68 字节对象经 `0x3C4D990`(`0x355F548`)、`0x3C4E098`(`0x355F554`)、 + `0x3C4D888`(`0x355F5D0`) 在 npcam 结构与 Halide `buffer_t` 之间来回转换; + 转换函数本体未展开(见未决事项 §8)。 + +### 1.4 传给滤波驱动的实际尺寸(verified) + +`0x355F75C` 起(参数装载): + +```asm +355f754: ldp x3, x7, [sp, #0x48] ; x3 = raisr 滤波器组描述符, x7 = 输出 TImage* +355f758: add x2, sp, #0x560 ; x2 = &compiled_params +355f75c: ldr x0, [sp, #0x4e0] ; x0 = input_ (1 通道 luma) +355f760: ldr x1, [sp, #0x468] ; x1 = 目标(输出)尺寸描述符 +355f764: add x4, sp, #0x474 ; x4 = &sharpen_params +355f768: mov w5, #2 ; scale = 2 (硬编码!) +355f76c: mov w6, wzr ; flag = 0 +355f770: bl 0x3589540 +``` + +- **per-shift 内核的整数倍率在此调用点上恒为 2**(verified)。 + 3x/4x 的内核存在但在这条路径不可达(`0x3589540` 的唯一调用者就是 `0x355F770`,verified)。 +- `x1` 给出最终输出尺寸;`0x3589540` 内 `0x35895A0 ldp w27, w28, [x21]` 用它建 RAISR 结果图。 +- `input_`(`[sp+0x4e0]`) 的维数即"低分辨率 luma"尺寸;hash 图尺寸 = `input_` 尺寸 × scale。 + +### 1.5 尺寸/对齐 + +- **未发现** 宽度向上取整到 128、高度取整到 16 之类的显式对齐代码:`0x3589540` 只用 + `[x21]`/`[x21+4]` 的原始宽高建 TImage(`0x35895A0..0x35895D4`);`0x358F370` 只用 + `ori_w*scale`、`ori_h*scale`(`0x358F3F8 mul w25, w8, w23`、`0x358F3FC mul w26, w9, w23`)。 + Halide AOT 内核自身会用 `halide_error` 做边界/负 extent 检查(如 `0x358A4BC..0x358A530` + 的空 buffer 路径、`0x358A5B4..0x358A5D0` 的空 buffer 检查),但**驱动层不做 128/16 对齐** + (verified:无对应对齐指令)。 +- 边缘扩展(edge extension)同样不在驱动层:驱动只把 dims 原样转成 + `halide_dimension_t`。内核内部的边界处理属于内核本体,本次不展开。 +- 每像素位深:内核名含 `Int16`(`0xBB5E80`);驱动层只做指针/维数搬运,不做量化 + (verified)。U12/Q14 的具体约定在 AOT 内核内部(未决,见 §8)。 + +### 1.6 内核参数结构(`buffer_t` 形态,verified) + +驱动把每个 TImage 展开成一个 **0x80 字节的栈结构**(`0x3589824` 里 4 份: +`sp+0x1B0`/`sp+0x120`/`sp+0x90`/`sp+0x00`): + +| 偏移 | 含义 | 证据 | +| --- | --- | --- | +| `+0x00` | 置 0(内核视为可选 buffer/device,配合 `+0x10` 判空) | `0x3589860` 附近 `stp q1,q1`;内核 `0x358A4DC ldr x9,[x19]; cbz x9` | +| `+0x10` | `void* host`(= TImage `[+0x20]`) | `0x3589848 ldr x8,[x1,#0x20]; 0x3589860 str x8,[sp,#0x1c0]`;内核对 `[x1,#0x10]` 做非空判定 `0x358A5B4` | +| `+0x20` | 8 字节常量,驱动填 `{0x6B20B30}`(普通 1 通道图)或 `{0x6B80E20}`(filters) | `0x3589850 ldr d0,[x9,#0xb30]`、`0x3589944 ldr d0,[x9,#0xe20]` | +| `+0x28` | `halide_dimension_t* dim`,指向 `+0x38` 的内联数组 | `0x358988C str x20,[sp,#0x1d8]`(`x20 = base+0x38`) | +| `+0x38` | `halide_dimension_t dim[4]`,每项 `{i32 min, i32 extent, i32 stride, i32 flags}` 16 字节 | 内核 `0x35C8D38 ldr x16,[x1,#0x28]` 后 `0x35C8D54 ldr d4,[x16]`、`0x35C8DB4 ldr d3,[x16,#0x10]` | + +`halide_dimension_t` 的 stride=16 与 `{min,extent,stride,flags}` 顺序由内核实证: +`0x35C8D44 ldp w10,w24,[x8,#0x4]`(extent0)、`0x35C8D50 ldr d15,[x8]`(min0+extent0)、 +`0x35C8D68 ldp w9,w10,[x8,#0x14]`(stride1+flags1)等(verified)。 + +**TImage 侧字段布局**(多函数一致,verified): + +| 偏移 | 含义 | +| --- | --- | +| `+0x00` | i32 宽(extent0) | +| `+0x04` | i32 高(extent1) | +| `+0x08` | i32 通道数(`num_channels`);驱动断言必须 == 1,串 `0x62DE7B "im.num_channels() == 1"`,文件串 `0x5FE748 "./research/vision/npcam/lib_common/buffer_common.h"`(`0x3589AF0..0x3589B24`) | +| `+0x0C` | i32 stride0 | +| `+0x10` | i32 stride1 | +| `+0x14` | i32 stride2 | +| `+0x20` | `void* data` | + +> 4 维描述符(filters)用的是**另一种对象**:extent 在 `+0x00,+0x04,+0x08,+0x0C`, +> stride 在 `+0x1C,+0x20,+0x24,+0x28`,host 在 `+0x48` +> (`0x3589930 ldr x8,[x3,#0x48]`、`0x3589950..0x3589980`)(verified)。 +> 也就是说 `0x3589824` 的第 4 个实参不是 TImage 而是 `0x355FFEC` 产出的滤波器组描述符。 + +### 1.7 整数倍率分派与错误串 + +`0x3589824`(FDE `0x3589824..0x3589BA8`)签名(verified): +`f(x0=input_ TImage*, x1=hash TImage*, x2=**未使用**, x3=filters 4D*, w4=scale, x5=result TImage*|NULL)`。 + +- `x2` 在整段函数体内**没有任何引用**(verified:仅作为形参被忽略)。 +- 三处 `num_channels()==1` 检查针对 `x1`(`0x3589838`)、`x0`(`0x3589880`)、`x5`(`0x35898CC`)。 +- 分派:`0x3589988 cmp w19,#4` → `0x358DC94`;`0x3589990 cmp w19,#3` → `0x358BEF0`; + `0x3589998 cmp w19,#2` → `0x358A240`;否则 `0x3589A10` 报 + `0x4FBD5E "Unsupported integer scale factor for per-shift RAISR filtering."` +- 内核调用实参(verified):`kernel(ctx, B(from x0), D(from x3), A(from x1), C(from x5))` + (`0x35899B8`:`x1=sp+0x120`、`x2=sp`、`x3=sp+0x1B0`、`x4=sp+0x90`) + ⇒ 与内核 buffer 声明序 `input_ / filters_ / hash_value_image_ / result` 完全一致。 +- `ctx` 由 `0x3589984 bl 0x427D35C` + `ldr x0,[x0]` 取得(Halide user_context)。 + +### 1.8 结果尺寸与 `flag`(w6) + +`0x3589540(x0..x7)` 内的三条 `0x3589824` 调用(verified): + +| 调用点 | x5(result) | 触发条件 | +| --- | --- | --- | +| `0x35895F4` | `x24` = 新分配 TImage | `(w24 & 1) == 0` 且 `0x35A27D4(x20) != 0` 且新建成功 | +| `0x3589630` | `x19` = 调用者给的输出图 | `(w24 & 1) != 0` | +| `0x3589670` | `NULL` | 上面两条都不成立 | + +`0x24C` 新图的尺寸来自 `x21`(`0x35895A0 ldp w27,w28,[x21]`),即**目标/输出尺寸** +(`0x355F230` 传的是 `[sp+0x468]`)。本路径 `w6 = 0`,因此走 `0x3589590` 分支。 + +--- + +## 2. `0x35894AC` 的 compiled-params:逐字段解码 + +`0x35894AC`(FDE size `0x94`)是一个**叶函数**,约定 `x8 = ¶ms`,把 0x70 字节结构写默认值。 +下表"默认值"均为该函数的立即数或它读取的 `.data` 常量原始字节(verified)。 + +| 偏移 | 宽度 | 默认值 | 写入指令 / 常量地址 | +| --- | --- | --- | --- | +| `+0x00` | i32 | `1` | `0x35894C0 str x9`(`x9=0x0000000C00000001`) | +| `+0x04` | i32 | `12` | 同上 | +| `+0x08` | u16 | `0` | `0x35894BC strh wzr` | +| `+0x09` | u8 | `0` | `0x3589524 strb wzr` | +| `+0x0A` | u8 | `0` | `0x35894E4 strb wzr` | +| `+0x0B` | — | 未写 | — | +| `+0x0C` | i32 | `4` | `0x3589528 str w10`(`w10=4`) | +| `+0x10` | u8 | `1` | `0x35894CC strb w9(1)` | +| `+0x11..0x13` | — | 未写 | — | +| `+0x14` | i32 | `0` | `0x358952C str wzr` | +| `+0x18` | 8B | `19 ef 02 be c3 68 b8 3c` ⇒ `{f32 −0.12786521, f32 +0.0225108918}` | `0x35894DC ldr d0,[0x6B30CF0]` → `0x35894E8 str d0,[x8,#0x18]` | +| `+0x20` | i32 | `3` | `0x35894F0/F4`(立即数 3) | +| `+0x24..+0x33` | 4×f32 | `{+0.0523100868, +0.00511798495, −0.0055033979, −0.0482351705}` | `0x35894EC ldr q0,[0x6BE0B00]` → `0x35894FC stur q0,[x8,#0x24]` | +| `+0x34` | f32 | `0.7f` | `0x3589504/08/10`(`0x3F333333`) | +| `+0x38` | 8B | `fd 33 89 be ae 32 3a 3e` ⇒ `{f32 −0.267974764, f32 +0.181833953}` | `0x3589500 ldr d0,[0x6B50E40]` → `0x3589530 str d0,[x8,#0x38]` | +| `+0x40` | u8 | `1` | `0x35894C8 strb w9(1)` | +| `+0x44` | i32 | `4` | `0x3589534 str w10(4)` | +| `+0x48` | i64 | `0` | `0x35894D4 stur q0,[x8,#0x48]`(覆盖 0x48..0x57) | +| `+0x50` | i64 | `0` | 同上 | +| `+0x54` | i32 | `43200`(`0xA8C0`) | `0x3589514/18` | +| `+0x58` | ptr | `0xBAB436` | `0x358951C/20/38`(`str x9,[x8,#0x58]`,覆盖上面 q0 写的 0x58..0x5F) | +| `+0x60` | i64 | `0` | `0x35894D8 stur q0,[x8,#0x58]` 的高半 | +| `+0x68` | i64 | `0` | `0x358950C str xzr` | + +常量原始字节(在 VA−0x4000 = 文件偏移处读取,并与 `llvm-objdump -s` 的 VA 行对照一致)(verified): + +- `0x6B30CF0`(file `0x6B2CCF0`):`19ef02be c368b83c b50799bd 844a0ebd` +- `0x6B50E40`(file `0x6B4CE40`):`fd3389be ae323a3e 1c4158be 98be23bd` +- `0x6BE0B00`(file `0x6BDCB00`):`1a43563d c5b4a73b d955b4bb 3e9245bd dfaad33c ...` +- `0x6B20B30`(file `0x6B1CB30`):`8a2e21bd 7bcca5bc`(普通 1 通道 buffer 的 `+0x20` 常量) +- `0x6B80E20`(file `0x6B7CE20`):`f8803fbd f1c12cbb`(filters buffer 的 `+0x20` 常量) +- `0x6BE0390`(file `0x6BDA390`):`e7e80739 3188403c d28a19bc 1103b03b` ⇒ `{0.00012961366, 0.011751221, −0.009371476, 0.005371459}`(composite 用,见 §5) + +### 2.1 语义(由消费者反推) + +`0x355FFEC`(`NanoRaisrDirectUpscaleAndRefineLumaMin` 的胶水,见 §1.2/§7)在入口处做: + +```asm +3560008: ldp w9, w10, [x0, #0x18] ; w9=[0x18], w10=[0x1C] +356000c: ldr w21, [x0, #0x3C] ; w21=[0x3C] +3560014: mul w9, w10, w9 ; w9 = [0x18]*[0x1C] +3560018: ldr w10, [x0, #0x20] ; w10 = [0x20] +356001c: mul w25, w21, w21 ; w25 = [0x3C]^2 +3560020: mul w23, w9, w10 ; w23 = [0x18]*[0x1C]*[0x20] -> 滤波器类别数 +3560024: ldr w9, [x0, #0x44] ; w9 = [0x44] -> shift 数 +356002c: mul w19, w23, w25 +3560030: mul w22, w19, w9 +3560044: lsl w9, w22, #1 +3560048: ldr w10, [x0, #0x54] ; 43200 +356004c: cmp w10, w9 +3560050: b.ne 0x3560094 ; 不匹配 -> 通用路径 +... +3560054: ldr x4, [x20, #0x58] ; 滤波器组指针 +3560058: mov w0, w21 ; mov w1, w21 ; mov w2, w23 ; w3 = [0x44] ; w5=1,w6=0,w7=0 +3560090: b 0x3560618 ; 通用 C++ per-shift 实现(ksize, ksize, nclass, nshift, bank, ...) +``` + +- 尺寸自洽条件:`2·[0x18]·[0x1C]·[0x20]·[0x3C]²·[0x44] == [0x54]`(verified)。 + 代入 `[0x20]=3`、`[0x44]=4`、`[0x54]=43200` ⇒ `[0x18]·[0x1C]·[0x3C]² = 1800`, + 唯一与 RAISR 语义自洽的整数解是 **`[0x18]=24`(角度档)、`[0x1C]=3`(相关度档)、 + `[0x3C]=5`(5×5 核)**,于是类别数 `= 24·3·3 = 216`,`216·25·4·2 = 43200` 字节(inferred,数学唯一解)。 +- 不匹配时打印 `0x4CAA71 "Inconsistent raw filter data size (%d) and size needed (%d)."` + (`0x3560338..0x3560360`,verified)。 +- `0x3560034/0x356003C` 读 `[x0+0x08]`、`[x20+0x09]` 两个 bool:任一非 0 直接走通用路径。 +- `0x3560104..0x3560110`:若 `[0x08]!=0`,`w23`(=类别数)被改成 `[0x3C]/2+1`; + `0x356011C..0x3560130`:若 `[0x09]!=0`,`w25`(=ksize²)被改成 `([0x18]+3)/4+1`。 + 这两处只在 bool 置位时生效,默认路径不启用(verified)。 +- `0x358F370`(hash 编排)读 `[x22+0x18]` 作为 **i32 标量**传给 hash 内核 + (`0x358F5B0 ldr w2,[x22,#0x18]`),读 `[x22+0x24..0x33]` 作为 **4 个 f32** + (`0x358F5A0 ldp s0,s1,[x22,#0x24]`、`0x358F5A8 ldp s2,s3,[x22,#0x2c]`)传给同一内核 + (verified)。 +- hash 内核元数据给出的标量名(`0xBB6B80..0xBB6C10`)为 + `num_angle_buckets_`、`min_strength_`、`max_strength_`、`min_coherence_`、`max_coherence_` + (verified)。即:`[0x18]`=num_angle_buckets,`[0x24]`=min_strength, `[0x28]`=max_strength, + `[0x2C]`=min_coherence, `[0x30]`=max_coherence(inferred:按寄存器/元数据顺序对齐)。 +- `0x359DAF4`(OrientationUint8ThinOptHalide)同样只取 `[x22+0x18]`(`0x358F554 ldr w2,[x22,#0x18]`, + verified)。 + +> **重要冲突(未决)**:`+0x18`/`+0x1C` 与 `+0x38`/`+0x3C` 被 `0x35894AC` 以 `str d`(8 字节) +> 写入,其字节是 **f32 对**;而 `0x355FFEC`、`0x358F370`、`0x359DAF4` 都把 `+0x18`/`+0x1C`/`+0x3C` +> 当 **i32** 读。按默认字节算 `[0x18]=0xBE02EF19`、`[0x1C]=0x3CB868C3`、`[0x3C]=0x3E3A32AE`, +> 上述尺寸自洽式不成立,通用路径会算出 `malloc(-1)`/巨量尺寸。可能的解释只有两种,静态阅读无法区分: +> (a) `+0x18/+0x1C` 与 `+0x38/+0x3C` 在设计上是"浮点视图",而默认初始化保留的是**未被使用/过期**的常量; +> (b) `0x35894AC` 的默认值只是占位,真实参数由本二进制中不存在的外部 tuning 注入。 +> 无论哪种,**这些 8 字节字段的默认值都不要照抄**;重实现时应使用 +> `(num_angle_buckets=24, num_coherence_buckets=3, num_strength_buckets=3, kernel=5, shifts=4)`。 +> 另注:hash 内核把该 i32 只取**最低字节**存入闭包 +> (`0x35928BC strb w8,[sp,#0x128]`,`w8 = [sp+0x58]` = 入参),默认字节的最低字节是 `0x19 = 25`。 +> 其余字段(`+0x00,+0x04,+0x0C,+0x10,+0x20,+0x24..0x34,+0x40,+0x44,+0x54,+0x58`)语义与默认值 +> 均有消费者实证(verified)。 + +--- + +## 3. 滤波器组(filter bank)布局 + +- **地址/长度**:VA `0xBAB436`,长度 `43200` 字节(= `params+0x54` 的值)(verified)。 + 位于 `.rodata`(VA == 文件偏移)。 +- **元素类型**:`int16`(verified,读取原始字节): + ``` + 0xBAB436: 38 -74 -251 49 -36 -95 193 1224 + -390 106 -249 956 3848 -750 198 32 + -269 -552 -48 13 -12 61 156 0 + ``` + 每 25 个 int16 成一组,组内出现中心大峰(`3848`、`3824`…),符合定点 `Q12`(中心 tap ≈4096) + 的 RAISR 5×5 核(inferred,量级证据)。 +- **索引顺序**(Halide 元数据 `0xBB5D40` 起,verified): + `filters_.extent.0 = 5`、`filters_.stride.0 = 1`、`filters_.min.0 = 0`、 + `filters_.stride.2 = 25`、`filters_.extent.2 = 216`、`filters_.stride.3 = 5400` + ⇒ 4 维 `[shift][216 class][ky 5][kx 5]`,即 + `idx = shift*5400 + cls*25 + ky*5 + kx`(int16 单位),`cls = angle*9 + coherence*3 + strength` + (后者的具体拆分属内核语义,inferred)。 +- **是否 scale 专用**:**所有倍率共用同一张表**(verified):`params+0x58` 只由 `0x35894AC` + 的常量设置(`0x358951C/20`),而该函数在 `0x355F230` 中每帧只调用一次且在 + `0x358F370`/`0x3589824` 之前;`0x3589540`/`0x358F370`/`0x3589824` 都不修改 `+0x58`。 + 由于本路径 scale 恒为 2(§1.4),实际被使用的是 **2x 组**;3x/4x 内核虽然存在,但驱动不会 + 在本调用点传入 3/4。 +- **表尾**:`0xBAB436 + 43200 = 0xBB5CF6`;其后 5 字节 0 填充,紧接 `.rodata` 串 + `0xBB5CFB "__user_context"`(verified,原始字节对照)。⇒ 表长确为 43200,无额外尾部。 +- **引用点唯一**:全二进制仅 `0x358951C` 把 `0xBAB436` 物化为指针(verified,与既有文档一致)。 + +--- + +## 4. `hash_value_image_` 的语义与驱动侧尺寸 + +- **驱动侧尺寸(verified)**:由 `0x358F370` 产出,返回给 `0x3589540` 的 `[sp+0x28]`, + 再作为 `x1` 传给 `0x3589824` → 成为 per-shift 内核的 `hash_value_image_`。 + ```asm + 358f454: ldr x8, [x24, #0x20] ; 源 luma host + 358f498: ldp w8, w10, [x24] ; w8=源宽, w10=源高 + 358f3f8: mul w25, w8, w23 ; 宽 * scale + 358f3fc: mul w26, w9, w23 ; 高 * scale + 358f404..428: new TImage(w1=0, w2=w25, w3=w26, w4=1, 0, 0) ; 1 通道 + ``` + ⇒ `hash_value_image_` 尺寸 = **(`ori_w*scale`, `ori_h*scale`)、单通道**; + 与 `result` 同尺寸(`0x3589540` 用 `[x1]`/`[x1+4]` 建结果图,`0x35895A0`)。 +- **元素类型**:驱动力只搬运指针与维数,不做量化(verified);`Int16` 由内核名 + `NanoRaisrUpscalePerShiftFRH2xInt16Opt5x5Halide`(`0xBB5E80`) 及 per-shift 内核的 + `halide_buffer_t` 类型字段(内核自填 `+0x20` 为 `Int(16) lanes=1`,`0x358A55C..0x358A56C` + 写入 `0x00000004_00011000`,低 32 位分解为 code=0/bits=16/lanes=1)(inferred)。 + 逐像素布局:单通道,每像素 1 个 int16,`stride = 1`(inferred,来自 `TImage` 通道数 1 + 内核 + `stride.0=1` 的同类约定)。 +- **分类数学在内核内部(明确)**:驱动**没有**任何梯度/角度/相干性计算。分类链是: + 1. `0x359DAF4` = **`OrientationUint8ThinOptHalide`**(名串 `0xBB7620`), + 输入 = `ori` 的 3 通道缓冲(`input_` 原尺寸),标量 = `params[0x18]`, + 输出 = `x19`(新建 `TImage(w1=1, w2=源宽, w3=源高, w4=3)`,3 通道,原分辨率)。 + (调用点 `0x358F55C`:`x1=sp+0x120`、`w2=[x22+0x18]`、`x3=sp+0x90`,verified) + 2. `0x3591F3C`/`0x3596470`/`0x359A41C` = **`HashFromOrientation{2,3,4}xThinOptHalide`**, + 缓冲区实参只有 2 个(`0x3591F58 cbz x3`、`0x3591F60 cbz x1`,verified), + `x1` = 3 通道的 orientation 图(维数取自 `[x1+0x28]` 的 dim2,元数据 + `ori_.extent.2 = 3`,`0xBB6E20`,verified);`x3` = 上采样尺寸的单通道图 + (`0x3591F64 ldr x28,[x3,#0x28]`,`0x3591F94 ldr d5,[x28,#0x10]` 取其 dim1 边界 ⇒ 输出边界)。 + 标量:`w2`(`0x3591F5C str w2,[sp,#0x58]`,仅取低字节写入 `halide_do_par_for` 闭包) + + `v0..v3` 四个 f32(闭包 `sp+0x98..0xA4`,`0x35928CC/28D0`,并行体 `0x358F794` + 在 `+0x10/+0x18` 读回,verified)。 + 3. 并行体 = `0x358F794`(经 `0x35928D8 ldr x1,[x1,#0x80]` 取 `GOT[0x61E7080] → 0x358F794`, + `0x35928DC bl 0x585F89C` = `halide_do_par_for`,verified)。 + ⇒ **哈希/分类数学 100% 在 AOT 内核内**;驱动只提供 `ori`(3ch 原尺寸)、1 个 i32、 + 4 个 f32,以及一个上采样尺寸的单通道输出缓冲。 + +--- + +## 5. composite 的输入与标量参数 + +### 5.1 调用链与实参 + +``` +0x3589540 ──0x3589594──> 0x35A27D4(sharpen_params) ; 探针 +0x3589540 ──0x358968C──> 0x35A2474(sharpen_params, raisr_luma, target_img, out_img) +0x35A2474 ──0x35A251C──> 0x35A1B24(raisr_luma, tmp, d0, d1) ; 内核 0x35B57F4 +0x35A2474 ──0x35A2540──> 0x35A1D80(target, tmp, target, sharpen, out) +0x35A1D80 ──0x35A1F70──> 0x35C8C54 = NanoRaisrCompositeHalide ; 失败串 0x6993B1 +0x35A2474 ──0x35A25A8/0x35A260C──> 0x35A216C(...) ; 内核 0x35A75B0 +0x35A2474 ──0x35A25E0──> 0x35A264C(img_a, img_b) -> 0x35B34C0 ; 拷贝/转换 +``` +(各 `bl` 地址见 `0x35a1b24_0x35a27f8.txt` 行 645/654/680/705/777,verified) + +`0x35A264C` 先逐字段比较两图的 `w/h/ch`(`0x35A264C..0x35A2678`,不等则返回 0), +再转成两个 Halide buffer 调 `0x35BC4C0`(`0x35A272C`)——与 `CopyImageHalide`(`0xBB8000`) +位置相邻,故 `0x35BC4C0 = CopyImageHalide`(inferred)。 + +### 5.2 composite 实参(`0x35A1F40..0x35A1F70`,verified) + +```asm +35a1f48: add x1, sp, #0x1d0 ; A <- x0 (0x35A1D80 的 arg0) +35a1f4c: add x2, sp, #0x140 ; B <- x1 +35a1f50: add x3, sp, #0xb0 ; C <- x2 +35a1f54: add x4, sp, #0x260 ; D <- 静态全局(见下) +35a1f58: mov w5, w19 ; fcvtzs( s0=sharpen[0x0C], #8 ) +35a1f5c: mov w6, w20 ; fcvtzs( s1=sharpen[0x10], #8 ) +35a1f60: mov w7, w21 ; fcvtzs( s2=sharpen[0x14], #4 ) +35a1f64: str x28, [sp, #0x10] ; E <- x4 (0x35A1D80 的 arg4 = 最终输出图) +35a1f68: strh wzr, [sp, #0x8] ; 第 5 个标量 = 0 +35a1f6c: strh w27, [sp] ; 第 4 个标量 = fcvtzs( s3=sharpen[0x18], #8 ) +35a1f70: bl 0x35c8c54 +``` +内核侧 ABI 实证(`0x35C8C54` 序言): +- 只用 `x1`、`x2`、`x4`、`x23`(= `[sp+0xb10]` = 调用者 `[sp+0x10]` = E)作为 buffer, + `0x35C8D38/0x35C8D3C/0x35C8D6C` 读 `[x+0x28]` 取 dims,`0x35C8F9C/0x35C9000/0x35C9010` + 读 `[x+0x10]` 取 host(verified)。 +- **`x3` 在整个内核体(`0x35C8C54..0x35CB418`)里从未作为基址寄存器出现** + (verified:`[x3` / `[x3]` 匹配数为 0;`x3` 仅被后续指令覆盖为临时值/字符串地址 `0xBB8400`)。 + ⇒ composite 的第 3 个指针实参是**未使用**的(驱动仍按 A 传入)。 +- `ldrh w9, [sp, #0xb00]`(`0x35C8CEC`)只读第 4 个标量;`[sp+0x8]` 的 0 未被读取(verified)。 + +因此 composite 的形参序列(按 ABI 观察)为: +`(ctx, x1=?, x2=?, <未用指针>, x4=?, w5, w6, w7, i16@[sp], i16@[sp+8], ptr@[sp+0x10]=output_image)`。 + +### 5.3 各 buffer 的来源 + +| 实参 | 内容 | 证据 | +| --- | --- | --- | +| `x1` (A) | `0x35A1D80` 的 arg0 = `0x35A2474` 的 arg2 = `0x3589540` 的 arg1 = `0x355F230` 的 `[sp+0x468]`(目标图像) | `0x35A1DA4..0x35A1E30` 从 arg0 建 A | +| `x2` (B) | `0x35A1D80` 的 arg1 = `0x35A2474` 的 arg1 = `0x3589540` 新建的 RAISR 亮度图 | `0x35895A4..0x35895D4` | +| `x4` (`randomness_lut`) | GOT 槽 `0x61E70A0`,`.rela.dyn` 中 `r_offset=0x61E70A0 → addend=0x7C59978`(**静态 `.data` 对象**) | `0x35A1DBC ldr x8,[x8,#0xa0]`;relocs.txt 第 158050 行(verified) | +| `x23`/E (`output_image`) | `0x35A1D80` 的 arg4 = `0x35A2474` 的 arg3 = `0x3589540` 的 arg7 = `0x355F230` 的 `[sp+0x50]`(最终输出 TImage) | `0x35A1EF4..0x35A1F3C`;`0x3589688`(verified) | + +**`randomness_lut` 细节**: +- 表体在 VA `0x7C59978`(文件偏移 `0x7C55978`),原始字节起始 + `0f 0f 0f 0a 0f 0f 0a 05 0f 0a 0a 05 0f 0f 05 00 ...`(verified,并与 `llvm-objdump -s` 的 + `7c59970 / 7c59980` 行一致)。对象首地址前 8 字节为 0(`0x7C59970`),故起点确为 `0x7C59978`。 +- 前 ≥ `0x1B6` 字节取值绝大多数落在 `{0x00,0x05,0x0A,0x0F}`(4 档量化), + 在偏移 `0x1B6` 之后出现 `0xCDCCCC3D` 等浮点数据,说明 LUT 对象在此结束或其后续为另一对象 + (verified 到"偏移 0x1B6 处首次出现非 {0,5,10,15} 的连续数据")。 +- **精确长度/周期未定**(见未决事项 §8):驱动为它构造的描述符 **dims 全为 0** + (`0x35A1DB4..0x35A1DE4` 用 `q4 = 0` 覆盖 D+0x00..0x2DF 全段,只写了 `+0x10` host、 + `+0x20` 常量、`+0x28` dims 指针,verified),所以内核必然用与 dims 无关的索引 + (硬编码周期/mod 或 unclamped 常量索引)读取该表。 + +**`census_fallback` / `census_raisr`**:不是实参。元数据里它们只有裸名字 +(`0xBB8480`、`0xBB84A0`),既无 `Input buffer ...` 也无 `Output buffer ...` 标签, +也没有 `.stride.` 条目;而 `image_fallback_`/`image_raisr_`/`randomness_lut`/`output_image` +四者都有标签(`0xBB8360/0xBB8380/0xBB83A0/0xBB83C0`,verified) +⇒ **census 变换是 `0x35C8C54` 内部的 Halide Func**,本次不展开(元素类型/半径/位宽未决)。 + +### 5.4 composite 标量参数的值与来源(verified) + +标量来自 `sharpen_params`(`0x355F230` 的 `sp+0x474`): + +| `sharpen_params` 偏移 | 来源 | 值 | +| --- | --- | --- | +| `+0x00` | `0x355F620 str s0,[sp,#0x474]`,其中 `s0 = ((s8 − 2.0f)·55.0f)/6.0f + 15.0f`(`0x355F5D4..0x355F610`,`55.0f = 0x425C0000`) | 2x 时 = `15.0f` | +| `+0x04` | `0x355F5DC str wzr` | `0.0f` | +| `+0x08` | `0x355F5E8 strb w29(1)` | `1`("启用";`0x35A27D4` 判据) | +| `+0x0C..+0x1B` | `0x355F614 ldr q1,[0x6BE0390]` → `0x355F618 stur q1,[x28,#0xb8]`(`x28 = sp+0x3C8` ⇒ `sp+0x480`) | `{0.00012961366, 0.011751221, −0.009371476, 0.005371459}` | + +复合标量(`fcvtzs` 定点转换,`0x35A1F0C..0x35A1F28`): + +| 内核形参(按位置) | 转换 | 数值 | +| --- | --- | --- | +| `w5` | `fcvtzs(s0, #8)`,`s0=[sharpen+0x0C]` | `(int)(0.00012961366·256) = 0` → `fallback_strength_ = 0`(inferred 名称对应) | +| `w6` | `fcvtzs(s1, #8)`,`s1=[sharpen+0x10]` | `(int)(0.011751221·256) = 3` → `artifact_correction_max_strength_ = 3`(inferred) | +| `w7` | `fcvtzs(s2, #4)`,`s2=[sharpen+0x14]` | `(int)(−0.009371476·16) = 0` → `artifact_map_scale_fixed_ = 0`(inferred) | +| `[sp]` i16 | `fcvtzs(s3, #8)`,`s3=[sharpen+0x18]` | `(int)(0.005371459·256) = 1` → `artifact_map_bias_fixed_ = 1`(inferred) | +| `[sp+8]` i16 | 常量 0 | `debug_output_select_ = 0`(inferred) | + +名称来源:`0xBB8180 "fallback_strength_"`、`0xBB81A0 "artifact_correction_max_strength_"`、 +`0xBB81E0 "artifact_map_scale_fixed_"`、`0xBB8200 "artifact_map_bias_fixed_"`、 +`0xBB8220 "debug_output_select_"`(verified,均在 composite 的元数据表窗口内、 +位于内核名 `0xBB82E0` 之前)。**具体哪一个名字对应哪一个位置属 inferred**—— +驱动与内核的绑定只能靠类型/位置推断,元数据表不携带顺序信息。 + +--- + +## 6. 色度 / 彩色处理 + +- **RAISR 只处理亮度**(verified): + `0x355F230` 先用 `0x3C4E098 → 0x3C50CBC = RgbToGray3ChOptHalideU8` 从 3 通道 RGB + 产生 luma(§1.2);随后整条 RAISR 链(orientation、hash、per-shift、composite) + 的每个缓冲都是**单通道**(`0x358F370` 建 1 通道 hash 图、`0x3589824` 的 + `num_channels()==1` 断言、`0x3589540` 建 1 通道结果图、composite 输出经 `TImage(w4=1)`)。 +- `RaisrUpsample` 的产物是**放大后的单通道亮度图**(`0x355F230` 的 `[sp+0x50]`, + 见 §1.4/§5.3)。 +- **与色度的重组不在 `0x355F230` 内**:该函数在整份二进制中只有唯一调用者 + `0x3364BC8`(位于 `0x33641DC..0x3365320`)(verified)。色度插值/重组发生在 + `0x33641DC` 里,本次未展开 ⇒ **未决**(见 §8)。 +- 相邻但**不属于**本 RAISR 路径的 finish 阶段内核: + `CensusHighFreqBlenderHalide`(`0xBB7900`)、`SharpenDOGHalide`(`0xBB7C40`)、 + `CopyImageHalide`(`0xBB8000`)、`OrientationUint8ThinOptHalide`(`0xBB7620`)。 + 其中 `OrientationUint8ThinOptHalide` 实际是 RAISR 链的第一站(§4), + `CopyImageHalide` 被 composite 链用作无锐化时的直通(§5.1)。 + +--- + +## 7. 调用顺序图(含精确尺寸) + +记源(RGB)尺寸为 `Sw × Sh`,目标尺寸 `Tw × Th`, +`scale = min(Tw/Sw, Th/Sh) ≥ 2`(本路径恒为 2)。 + +``` +RaisrUpsample 0x355F230 +├─ 0x355F2C4..2DC scale = min(Tw/Sw, Th/Sh) ; 要求 scale ≥ 2.0(0x604392) +├─ 0x427D2F0 + 0x355F40C 设置 Halide user_context = x1 +├─ new(0x68)×2: 0x355F428(x24=2Sw×2Sh) / 0x355F4E0(x25=Sw×Sh) +│ (0x355F444 stp x19(=2Sw),… / 0x355F448 stp x20(=2Sh),…) +├─ 0x3C4D990 0x355F548 npcam→Halide 适配 +├─ 0x3C4E098 0x355F554 → 0x3C50CBC RgbToGray3ChOptHalideU8(rgbx_in_ → result) +│ ⇒ input_y : 1ch, Sw×Sh, Int16/定点 +├─ 0x35894AC 0x355F55C compiled_params = 默认值(0x70B @ sp+0x560) +├─ 0x355FFEC 0x355F568 compiled_params → 0x240 = filters 描述符(见 §2.1) +│ · 尺寸自洽检查:2·[0x18]·[0x1C]·[0x20]·[0x3C]²·[0x44] == [0x54](=43200) +│ · 走 0x3560618 / 通用路径产出 4 维 filters 描述符 +├─ 0x3C4D888 0x355F5D0 → [sp+0x4E0] = input_ (1ch) +├─ 0x3589540 0x355F770 (x0=input_, x1=[sp+0x468]=目标图, x2=¶ms, +│ x3=filters, x4=&sharpen, w5=2, w6=0, x7=输出图) +│ │ +│ ├─ 0x358F370 0x3589588 (x0=input_, x1=¶ms, w2=scale, x8=&out) +│ │ ├─ A = new TImage(w1=1, Sw, Sh, 3, 0, 0) ; 0x358F3A4..0x358F3CC +│ │ ├─ B = new TImage(w1=0, Sw*scale, Sh*scale, 1,0,0); 0x358F404..0x358F42C +│ │ ├─ 0x359DAF4 OrientationUint8ThinOptHalide 0x358F564 +│ │ │ (ori=input_(3ch 视图), w2=params[0x18], out=A) ⇒ A : 3ch, Sw×Sh +│ │ ├─ 2x: 0x3591F3C HashFromOrientation2xThinOptHalide 0x358F5B8 +│ │ │ (x1=A(3ch), x2=params[0x18], x3=B, v0..v3=params[0x24..0x30]) +│ │ │ ⇒ B : 1ch, Sw*2 × Sh*2 = hash_value_image_ ; 经 *out 返回 +│ │ └─ 并行体 0x358F794(halide_do_par_for,GOT[0x61E7080]) +│ │ +│ ├─ 0x35A27D4 0x3589594 探针:sharpen[+0x08]!=0 || max(sharpen[+0],sharpen[+4])>0 +│ ├─ 0x35895A0..5D4 result = new TImage(0, Tw, Th, 1, 0, 0) ; dims 取自 x1=[sp+0x468] +│ ├─ 0x3589824 0x35895F4 scale==2 → 0x358A240 +│ │ kernel(ctx, input_(Sw×Sh,1ch), filters(4D), hash(Sw*2×Sh*2,1ch), result(Tw×Th,1ch)) +│ │ 缓冲区校验:x1/x0/x5 的 [buf+0x08]==1,否则 +│ │ 串 0x62DE7B "im.num_channels() == 1" / 文件 0x5FE748 buffer_common.h +│ │ 倍率非 2/3/4 ⇒ 串 0x4FBD5E "Unsupported integer scale factor ..." +│ ├─ 0x35A2474 0x358968C (x0=&sharpen, x1=result, x2=目标图, x3=输出图) +│ │ ├─ 0x35A1B24 0x35A251C → 0x35B57F4 (result, tmp, d0, d1) [可选] +│ │ ├─ 0x35A1D80 0x35A2540 → 0x35C8C54 NanoRaisrCompositeHalide 0x35A1F70 +│ │ │ x1=目标图(帧缓冲), x2=RAISR 亮度图, x3=<未用>, x4=randomness_lut(0x7C59978), +│ │ │ w5=0, w6=3, w7=0, i16[sp]=1, i16[sp+8]=0, [sp+0x10]=最终输出图 +│ │ │ 4 个 buffer 的 dims 全由驱动给出(randomness_lut dims 全 0) +│ │ └─ 0x35A216C 0x35A25A8/0x35A260C → 0x35A75B0 [可选] +│ │ 无锐化时:0x35A264C → 0x35BC4C0 CopyImageHalide(w/h/ch 必须一致) +│ └─ 0x355FFEC 已产出 filters;0x355F774 失败 → 0x355FF38 +├─ 日志:0x355F834 " Raisr %dx (%.0f ms)."(串 0x5ABC9C) +└─ 失败时打印源码级调用串 0x58BF21(0x355FF40) +``` + +尺寸小结(全部 verified,除标注外): + +| 缓冲 | 尺寸 | 通道 | 元素 | +| --- | --- | --- | --- | +| `input_` | `Sw × Sh` | 1 | Int16 域(内核名 `Int16`) | +| `ori_`(orientation) | `Sw × Sh` | 3 | 内核决定(`ori_.extent.2 = 3`);名串含 `Uint8` | +| `hash_value_image_` | `Sw·scale × Sh·scale` | 1 | Int16 | +| `result` / RAISR 亮度 | `Tw × Th`(本路径 `= 2Sw × 2Sh`) | 1 | Int16 | +| `filters_` | `[shift][216][5][5]` = 4×216×25 int16 = 43200B | — | Int16 | +| `randomness_lut` | 未知(dims 全 0;静态表 @`0x7C59978`) | — | 字节域,取值以 `{0,5,10,15}` 为主 | +| `image_fallback_` | `Tw × Th` | 1 | Int16 | +| `output_image` | `Tw × Th` | 1 | Int16 | + +--- + +## 8. 未决事项(未决) + +1. **`compiled_params` 的 `+0x18/+0x1C` 与 `+0x38/+0x3C` 类型冲突(最高优先级)** + - 事实:`0x35894AC`(`0x35894DC/0x3589530`)以 `str d` 把 `0x6B30CF0`、`0x6B50E40` + 的 8 字节写进这两个槽;字节是 f32 对(`{−0.12786521, +0.0225108918}`、 + `{−0.267974764, +0.181833953}`)。 + - 事实:`0x355FFEC`(`0x3560008/0x356000C`)、`0x358F370`(`0x358F5B0`)、 + `0x359DAF4`(`0x358F554`) 都把 `+0x18`/`+0x1C`/`+0x3C` 当 i32 用,并由 + `2·[0x18]·[0x1C]·[0x20]·[0x3C]²·[0x44] == 43200` 反推需要 `(24, 3, 5)`。 + - 未决原因:静态阅读无法判断是"默认初始化的常量已过期/仅作占位"还是"存在外部 + tuning 注入路径"。**重实现建议**:直接用 `(24, 3, 3)` 类别三元组、ksize `5`、 + shifts `4`,并把 `+0x54` 校验为 `2·24·3·3·25·4 = 43200`。 + - 未决的可判定性:需要动态验证(在 `0x356004C`/`0x3560150` 看实际取值)或找到外部注入点。 +2. **`randomness_lut` 的精确长度与索引方式**。已知表体 VA `0x7C59978`(静态 `.data`)、 + 驱动传给 composite 的 dims 全 0、前 ≥0x1B6 字节以 `{0,5,10,15}` 为主。 + 表长/周期/内核索引表达式在 `0x35C8C54` 内部,本次未展开。 +3. **census 变换的定义**:`census_fallback`/`census_raisr` 是 composite 内核内部 Func + (无 buffer 标签),其半径/位宽/元素类型全在内核内,未展开。 +4. **色度重组位置**:`0x355F230` 的唯一调用者 `0x3364BC8`(`0x33641DC..0x3365320`) + 未展开,因此"RAISR 亮度结果如何与色度插值结果合并"未定。 +5. **`0x355FFEC` 的通用路径细节**:`0x3560618`(通用 per-shift 实现,入参 + `(ksize, ksize, nclass, nshift, bank, 1, 0, 0)` + 0x58 字节滤波器描述符)与 + `0x356071C` 的算法未展开;`[x0+0x08]`/`[x0+0x09]` 两个 bool 开启后的尺寸改写 + (`0x3560104/0x356011C`)语义未定。 +6. **`input_` 的"低分辨率"来源链**:`x0` 于 `0x355F75C` 取自 `[sp+0x4E0]`,它由 + `0x3C4D888`(`0x355F5D0`)从 `sp+0x490` 对象构造,而 `sp+0x490` 的字段来自 + `0x355F4E0` 分配的 0x68 字节对象与 `0x3C4D990` 的产物。`0x3C4D888/0x3C4D990` + (npcam TImage/allocator 适配器)未展开,因此"哪一步把源图降到 Sw×Sh"未定 + (只能确定 `input_` 尺寸为 `Sw×Sh`,而 `Tw×Th` 由 `x2` 打包传入)。 +7. **`0x35A1B24` → `0x35B57F4` 与 `0x35A216C` → `0x35A75B0` 两个内核的身份**: + 两者都在 composite 链上被 `0x35A2474` 按 `sharpen[+0x10] > 0` / `sharpen[+0x08]` + 条件调用,但名称表未给出确定名字(`0x35B57F4` 与 `SharpenDOGHalide`/`CensusHighFreqBlenderHalide` + 的关系未证实)。 +8. **per-shift 内核的精确像素域(U12/Q14 约定)与边界填充**在内核内部,驱动层不体现。 +9. `0x35C8C54` 第 3 个指针实参被内核完全忽略(`x3` 零引用)。驱动传的是与 `x1` 相同的 + 目标图。是否对应某个"声明了但未使用"的 `ImageParam`,静态阅读无法确认。 + +--- + +## 9. 重实现要点(由上文直接得出,全部有据) + +1. 只在 `resample_rate = min(Tw/Sw, Th/Sh) ≥ 2.0` 且 `scale` 为整数时启用;本版驱动恒用 2 + (`0x355F768 mov w5, #2`)。 +2. luma 用 `RgbToGray3ChOptHalideU8`(等价实现即可)从 RGB 得到,尺寸 `Sw×Sh`。 +3. hash 图与 RAISR 结果图是**上采样尺寸**(`Sw·2 × Sh·2`)、单通道、Int16。 +4. 滤波器组:`216 classes × 25 taps × 4 shifts` 的 int16,索引 + `shift*5400 + cls*25 + ky*5 + kx`;所有倍率共用一张表。 +5. 类别数三元组用 `(24, 3, 3)`,ksize 5,shifts 4;驱动力只做尺寸一致性校验 + `2·nclass·ksize²·nshift == bank_bytes`。 +6. composite 的 4 个有效输入为 `(目标图, RAISR 亮度图, randomness_lut, 输出图)`, + 另有 3 个 i32 + 2 个 i16 标量;无锐化时退化为 `CopyImageHalide`。 +7. `randomness_lut` 必须作为静态常量表随内核一起携带(来源 VA `0x7C59978`), + 且内核以与 dims 无关的方式索引它。 diff --git a/docs/research/mgc-raisr-output-upscale.md b/docs/research/mgc-raisr-output-upscale.md new file mode 100644 index 00000000..8aa88a58 --- /dev/null +++ b/docs/research/mgc-raisr-output-upscale.md @@ -0,0 +1,783 @@ +# MGC V25 RAISR 输出放大:原版事实与接入设计 + +## 结论 + +原版 MGC 的 finish 输出放大只有两条互斥实现:`LancetUpsample`(Lanczos 系) +与 `RaisrUpsample`(RAISR)。Photon 已实现前者(`RawOutputPass` 的 Lanczos-3 +输出重采样,`RawOutputGeometry.resample`),本文件记录后者的原版事实与移植设计。 + +RAISR 在原版里不是单个内核,而是一组 Halide AOT 内核加 npcam 胶水代码: + +| 内核 | 作用 | 输入 → 输出 | +| --- | --- | --- | +| `NanoRaisrUpscalePerShiftFRH2xInt16Opt5x5Halide` | 2x per-shift 5×5 滤波 | `input_`,`filters_`,`hash_value_image_` → `result` | +| `NanoRaisrUpscalePerShiftFRH3x/4xInt16Opt5x5Halide` | 3x/4x 同上 | 同上 | +| 哈希内核(入口 `0x3591F3C`,无独立名字串) | 由 `ori_`/`up_ori` 生成滤波类别索引 | `ori_`,`up_ori` → `result`(`hash_value_image_`) | +| `NanoRaisrCompositeHalide` | 用 fallback/census/randomness 抑制伪影 | `image_fallback_`,`image_raisr_`,`randomness_lut`,`census_fallback`,`census_raisr` → `output_image` | +| `CensusHighFreqBlenderHalide`、`SharpenDOGHalide`、`CopyImageHalide`、`OrientationUint8ThinOptHalide` | 同一条 finish 链上的相邻内核(polysharp/blender) | 见名表 | + +因此“新增 MGC 的 RAISR”= 移植哈希、2x per-shift、composite 三个 AOT 内核, +外加重新实现 npcam 驱动胶水(cheap upscale、hash 输入、per-shift 参数、 +census/randomness 输入),并与现有 Lanczos 输出放大互斥。 + +## 来源与可复核地址 + +- 二进制:`.codex-tmp/mgc_v25/apk/lib/arm64-v8a/libgcastartup.so` +- SHA-256:`76966e7c150dfcb2795ea5b2119827a7e90b13d8c03035dbc4de583d9d12eaa6`(MGC 9.7.047 V25) +- 地址为 ARM64 ELF 虚拟地址;`.rodata` 的 VA 与文件偏移相同。 +- 本次新增的逆向辅助脚本(未纳入构建): + `.codex-tmp/ida/mgc_v25/raisr_recon/{scan_adrp.py,scan_relocations.py,eh_frame_ranges.py}` + (`eh_frame_ranges.py` 解析 `.eh_frame` 得到全部函数边界,输出 `fde_ranges.txt`) + +### 关键字符串 + +| 地址 | 内容 | 代码引用 | +| --- | --- | --- | +| `0x4F258F` | `disable_raisr` | `0x5B97090` | +| `0x4FBD5E` | `Unsupported integer scale factor for per-shift RAISR filtering.` | `0x3589A10` | +| `0x58BF21` | `NanoRaisrDirectUpscaleAndRefineLumaMin( *input_y_npcam, cheap_upscaled_y_npcam.get(), compiled_params, nano_raisr_filters, sharpen_params, raisr_rescale_factor, disable_sharpening_and_blending_pass, raisr_upscaled_y_npcam)` | `0x355FF40` | +| `0x5ABC9C` | ` Raisr %dx (%.0f ms).` | `0x355F834` | +| `0x5C785E` | `raisr` | `0x5B94744` | +| `0x5F52B8` | `RaisrUpsample` | `0x355F258` | +| `0x604392` | `Upsample: RaisrUpsample expects a resample_rate >= %f but was %f` | `0x355F2F4` | +| `0x6993B1` | `RaisrCompositer failed.` | `0x35A1F78` | +| `0x6A9022` | `research/vision/npcam/lib_raisr/nano_raisr/nano_raisr_direct_5x5.cc` | `0x3589720` | +| `0x633522` | `research/vision/npcam/lib_enhance/polysharp_raisr2020.cc` | `0x3576940` 等 | + +`Upsample: LancetUpsample expects a resample_rate >= %f but was %f` 与 +`Resample(finished.u8_image(), LanczosKernel<1>, target, context, {resample_rate, resample_rate})` +确认原版的 Lanczos 侧实现;`InitParams_finish_lancet_enabled` 是原版的 lancet 开关。 + +### 内核名表(`0xBB5E80..0xBB8500`,均无代码/数据引用,仅调试名) + +- `0xBB5E80` `NanoRaisrUpscalePerShiftFRH2xInt16Opt5x5Halide` +- `0xBB6340` `NanoRaisrUpscalePerShiftFRH3xInt16Opt5x5Halide` +- `0xBB6800` `NanoRaisrUpscalePerShiftFRH4xInt16Opt5x5Halide` +- `0xBB82E0` `NanoRaisrCompositeHalide` +- 同区还有 `CensusHighFreqBlenderHalide`、`SharpenDOGHalide`、`CopyImageHalide`、 + `OrientationUint8ThinOptHalide`。 + +内核 buffer 名与维度(Halide `buffer_t` 元数据): + +- 2x:`0xBB5D40..0xBB61A0`:`input_`、`filters_`、`hash_value_image_`、`result`; + `filters_` 的 `extent.2 = 216`、`stride.3 = 5400` ⇒ `[shift][216 filter][5][5]` + (216 = RAISR 的 24 角度 × 3 相关度 × 3 强度类)。 +- 3x:`0xBB6200..0xBB6660`;4x:`0xBB66C0..0xBB6B20`(结构相同)。 +- 哈希内核:`0xBB6B60..0xBB6E60`:`ori_`、`up_ori`、`result`。 +- composite:`0xBB82E0..0xBB84F0`:`image_fallback_`、`image_raisr_`、`output_image`、 + `randomness_lut`、`census_fallback`、`census_raisr`,另有 + `artifact_correction_max_strength_`、`artifact_map_scale_fixed_`、 + `artifact_map_bias_fixed_`、`fallback_strength_`、`debug_output_select_`。 + +### 代码结构(`.eh_frame` 已确认的函数边界) + +| 地址(范围) | 角色 | +| --- | --- | +| `0x355F230` | `RaisrUpsample` 阶段入口 | +| `0x355F2E0..0x355F2E8` | `fmov s0,#2.0; fcmp s8,s0; b.pl` ⇒ **要求 resample_rate ≥ 2.0**;否则报错(`0x355F2F4`)后继续 | +| `0x355F55C` / `0x355F568` / `0x355F770` | 依次调用 `0x35894AC`(参数默认值)、`0x355FFEC`(`NanoRaisrDirectUpscaleAndRefineLumaMin`)、`0x3589540` | +| `0x35894AC` (0x94) | 参数结构默认值:`+0x54 = 43200`、`+0x58 = 0xbab436`(滤波器组指针)、`+0x34 = 0.7f`、`+0xC/+0x44 = 4`、`+0x20 = 3` | +| `0x3589540` (0x1FC) | TImage 入口:`0x3589588 → 0x358F370`(哈希)、`0x35895F4/0x3589630/0x3589670 → 0x3589824`(per-shift)、`0x358968C → 0x35A2474`(composite 链)、`0x3589594 → 0x35A27D4` | +| `0x3589824` (0x384) | 整数倍率分派:`cmp w19,#2/#3/#4` → `0x358A240`/`0x358BEF0`/`0x358DC94`;其它倍率报 `Unsupported integer scale factor...`。调用约定:`x0 = user_context`,`x1..x4 = 4 个 buffer_t*` | +| `0x358F370` (0x424) | 哈希编排;`0x358F5B8 → 0x3591F3C`(哈希内核) | +| `0x35A2474` (0x1D8) | composite 链入口,调用 `0x35A1B24`、`0x35A1D80`、`0x35A216C`;`0x35A1F78` 引用 `RaisrCompositer failed.` | +| AOT 内核(无 CFI) | 2x ≈ `0x358A1F8..0x358B900`;3x ≈ `0x358BEA8..0x358D53x`;4x ≈ `0x358DC4C..0x358F34x`;哈希入口 `0x3591F3C`,范围 ≈ `0x3591E00..0x3592C00`;composite 范围 ≈ `0x35C9000..0x35CB418` | + +### 静态数据 + +- 滤波器组:`0xBAB436`,`43200` 字节 = `21600` 个 int16 = 4 shift × 216 filter × 25 tap, + Q12(每个滤波器 25 抽头之和落在 4104..4113,即 2^12 附近的量化)。 + 仅被 `0x358951C` 引用(`0x35894AC` 的默认参数)。 + 四个 shift 互为水平/垂直翻转,正是 2x 上采样的 per-shift 亚像素相位网格。 + 已提取为 tracked 资源 `app/src/main/cpp/mgc_denoise_static/mgc_raisr_filters.bin` + (SHA-256 `0ace2b67b820732dd0cccebeea867521cf9144721196574918f618a1da9ed3c6`), + 可用 `scripts/research/extract_mgc_raisr_filters.py` 复现(脚本会校验源 SHA-256 与 + Q12 归一化范围)。 +- `randomness_lut`:`0x7C59978`(`.data`,文件偏移 = VA−0x4000),**256 字节**的 16×16 dither 表, + 取值只有 {0,5,10,15},0x100 之后为 0 填充。已提取为 tracked 资源 + `app/src/main/cpp/mgc_denoise_static/mgc_raisr_randomness_lut.bin` + (SHA-256 `dd3e825c6571e9371bc94c3b781b6b6a652eaeb3a1b20544a61e0f573519398b`), + 可用 `scripts/research/extract_mgc_raisr_randomness_lut.py` 复现。 + 长度由数据本身判定;内核具体索引表达式仍未证明(见未决事项)。 + +### Halide runtime 宿主符号 + +与既有 GuidedUpsample 移植一致:`halide_malloc 0x5F91100`、`halide_free 0x5F9111C`、 +`halide_trace 0x5F93F88`、`halide_do_par_for 0x0585F89C`。 + +## Photon 接入设计 + +### 与 Lanczos 的互斥 + +- `MultiFrameConfig` 增加输出放大算法枚举:`LANCZOS3`(默认)/ `MGC_RAISR`。 +- 倍率语义(已确认):选择 RAISR 时输出倍率锁定 `2.0`(RAISR 只支持 ≥2x 的整数 + per-shift 滤波,本 App 倍率上限 2.0,故只有 2x 可达);滑杆置灰并给出原因文案。 + 切回 `LANCZOS3` 后滑杆恢复 1x–2x 连续可调。 +- 管线接入点唯一:`RawOutputGeometry.resample` 为真时,`RawOutputPass` 走 + Lanczos 还是 RAISR 由算法枚举决定;同一时刻只跑一种,绝不同时叠加。 + +### 内核移植(沿用仓库既有套路) + +1. `scripts/research/generate_mgc_raisr_static_asm.py`:按 + `generate_mgc_guided_upsample_static_asm.py` 的方式,从固定 SHA 的 + `libgcastartup.so` 提升 2x per-shift、哈希、composite 三个闭包,产出 + `mgc_denoise_static/mgc_raisr_*_capsule.bin` 与 `.S.in`。 +2. `CMakeLists.txt` 增加 capsule SHA-256 校验与静态库目标。 +3. 原生侧三个文件分工: + - `mgc_raisr_driver.cpp`:驱动胶水,导出 `photon_mgc_raisr_upscale_rgba` + (单次整帧,探针用)与 `photon_mgc_raisr_upscale_rgba_banded`(分带,探针比对用)。 + - `mgc_raisr_bands.h`:分带运行器与共享量化 `ToU8`(模板,driver 与 JNI 共用)。 + - `mgc_raisr_jni.cpp`:Kotlin 入口,负责取位图/缓冲、格式与尺寸校验、像素格式转换。 +4. Kotlin 侧新增 `MgcRaisrUpscale`(对齐 `MgcGuidedUpsample` 的所有权/释放模型), + 只持有"调用方已有的帧"和"要的 2x 图"两个 Bitmap,不申请任何 scratch、不做逐像素循环。 + +### 驱动胶水 + +需在原生侧重新实现(对应 `0x3589540`/`0x3589824`/`0x358F370`/`0x35A2474`): + +1. 从最终 sRGB 结果取 luma(`ori_`),做与 `Lanczos` 同源的低分辨率准备; +2. cheap upscale 得到 `up_ori`(fallback luma); +3. 哈希内核:`ori_` + `up_ori` → `hash_value_image_`; +4. 2x per-shift 内核:`input_` + `filters_` + `hash_value_image_` → RAISR luma; +5. census(`census_fallback`/`census_raisr`)与 `randomness_lut`; +6. composite:fallback + RAISR + census + randomness → `output_image`; +7. 与色度(沿用现有重采样)合成,替换原 Lanczos 的亮度重采样结果。 + +## 实施状态 + +已完成(`compileDefaultDebugKotlin` 通过): + +- `raw/RawOutputUpscaleMode.kt`:`LANCZOS3`(默认)/ `MGC_RAISR`,RAISR 固定 2x + (`RAISR_REQUIRED_OUTPUT_SCALE = 2f`),并提供 `resolveOutputScale` / `usesRaisr`。 +- `RawOutputScaling`:新增 `rawDisplayOutputUpscaleMode` 属性键,`read` 按算法归一化倍率, + `readUpscaleMode` 兼容旧照片(缺省即 Lanczos-3)。 +- `RawOutputGeometry`:`upscaleMode` 参数、`outputScale`、`raisrUpsample`; + RAISR 选中时几何与支持区都按 2x 求解。 +- `RawDemosaicProcessor`:`rawOutputScale` 旁新增 `rawOutputUpscaleMode`(5 处签名 + 4 处内层转发), + 并在 `RAW_OUTPUT_RESAMPLING` 日志里输出 `upscale=` 与 `raisr=`。 +- `MediaMetadata.rawOutputUpscaleMode`:拍摄时由 `CameraViewModel` 从偏好写入; + `GalleryManager` 用 `RawOutputScaling.write(..., metadata.rawOutputUpscaleMode)` 持久化到 DNG; + `PhotoProcessor` 与 `GalleryManager` 的 9 处渲染调用点用 `RawOutputScaling.readUpscaleMode(...)` 还原。 +- 偏好:`raw_output_upscale_mode` 键 + `saveRawOutputUpscaleMode`(选中 RAISR 时把倍率写为 2x), + `saveRawMaxOutputScale` 按当前算法归一化;`CameraViewModel.rawOutputUpscaleMode` + `setRawOutputUpscaleMode`。 +- 设置界面:专业模式「图像质量」组内新增「输出放大算法」二选一;RAISR 选中时输出倍率滑杆置灰, + 描述文案切换为锁定说明。 +- 字符串:`values`、`values-zh-rCN`、`values-zh-rTW`、`values-zh-rHK`、`values-b+zh+Hant`、`values-ja` + (新增 5 条:模式标题/说明/两个选项/锁定说明);其余语言沿用既有回退英文的约定。 + +待完成: + +1. AOT 内核与静态资源 —— **已完成并验证**:五个内核符号 + `photon_mgc_raisr_{rgb_to_gray,orientation,hash,upscale_2x,composite}` 与两个数据符号 + `photon_mgc_raisr_{filters,randomness_lut}` 均已链接进 `libmy-native-lib.so` + (Debug `.so` 符号表可见,且两个 `.bin` 的内容在 `.so` 中各出现且仅出现一次、字节一致)。 + capsule SHA-256 `d6c952ed…f7cb` 与 CMake 校验一致,`./gradlew buildCMakeDebug` 通过。 +2. 驱动胶水(详见 `docs/research/mgc-raisr-driver-spec.md` §7/§9):五个内核与两张静态表 + 都已就绪,尚需在原生侧按调用顺序把它们串起来(见该文 §7 的调用顺序图)。 + 仍未定的一项: + - **色度重组**:位于 `0x355F230` 之外(唯一调用者 `0x3364BC8`),未展开; + 需要决定继续逆向还是采用明文记录的等价色度上采样方案。 + - `mgc-raisr-driver-spec.md` §8 的部分未决项(compiled-params `+0x18/+0x1C/+0x38/+0x3C` + 的 f32 写入 / i32 读取冲突)静态不可判定,需要按仓库既有 `probe_*` 做法做动态验证。 +3. 管线接入:RAISR 是对亮度做的全图整数倍放大,不能像 Lanczos 那样在 + `RawOutputPass` 的分块着色器里逐块完成。需要以 `MgcGuidedUpsample` 同样的 + “读回 → 原生内核 → 上传” 模式,在 `renderOutputPass` 之后按全图执行,并把 + `RawTilePlanner` 的 `supportPx`/`processingPeriod` 扩展到 5x5 滤波与降采样上下文所需范围。 +4. 端到端验证(真机出图对比)。 + +### AOT 模块的 worker/wrapper 布局(本轮已解出) + +Halide AOT 的并行任务函数指针集中在一张表 `0x61E7068..0x61E7160`(`.got`,每项 8 字节, +`R_AARCH64_RELATIVE`)。wrapper 用 `adrp x1, 0x61E7000` + `ldr x1, [x1, #off]` 取出 +worker 指针后 `bl halide_do_par_for`。据此得到的模块布局是严格递增的 +“worker 区间 + wrapper 区间”配对: + +| 内核 | worker 区间 | wrapper 区间 | 表项 | +| --- | --- | --- | --- | +| 2x per-shift | `0x3589BF0..0x358A240` | `0x358A240..0x358B830` | `0x61E7068` | +| 3x per-shift | `0x358B830..0x358BEF0` | `0x358BEF0..0x358D534` | `0x61E7070` | +| 4x per-shift | `0x358D534..0x358DC94` | `0x358DC94..0x358F370` | `0x61E7078` | +| hash | `0x358F794..0x3591F3C` | `0x3591F3C..0x3592C10` | `0x61E7080` | +| orientation | `0x359B0A8..0x359DAF4` | `0x359DAF4..0x35A1B24` | `0x61E7098` | +| rgb→gray | `0x3C50BC8..0x3C50CBC` | `0x3C50CBC..0x3C516C0` | `0x61E8630` | +| composite | `0x35BD0DC`、`0x35BF998`、`0x35C2254`、`0x35C29FC`、`0x35C2FD0`、`0x35C4A44`、`0x35C64E4`、`0x35C6C30`、`0x35C86A0` 各 worker(共 9 个) | `0x35C8C54..0x35CB418` | `0x61E7120`..`0x61E7160` | + +导出符号与调用约定(wrapper 处实证): + +```text +photon_mgc_raisr_rgb_to_gray(user_context, rgbx_in_, result) // 0x3C4E164 调用点 +photon_mgc_raisr_orientation(user_context, input_3ch, num_angle_buckets, result) // 0x358F564 调用点,w2 = params[0x18] +photon_mgc_raisr_hash(user_context, ori_, num_angle_buckets, min_strength, max_strength, min_coherence, max_coherence, result) +photon_mgc_raisr_upscale_2x(user_context, input_, filters_, hash_value_image_, result) +photon_mgc_raisr_composite(user_context, image_fallback_, image_raisr_, image_artifact_fallback, randomness_lut, + fallback_strength_q8, artifact_correction_max_strength_q8, artifact_map_scale_q4, + artifact_map_bias_q8, debug_output_select, output_image) +``` + +注意:灰度内核的 task slot 在**另一张表** `0x61E8000`(`[x1,#0x630]`),不是 RAISR 模块的 +`0x61E7000`;早期把 `0x61E7630` 当它是错的,正确 worker 为 `0x3C50BC8`。 + +证据:2x wrapper 在 `0x358B30C` 取 `[x1,#0x68]`、3x 在 `0x358CFB0` 取 `[x1,#0x70]`、 +4x 在 `0x358ED7C` 取 `[x1,#0x78]`、hash 在 `0x35928D8` 取 `[x1,#0x80]`,随后都在 +`bl 0x585F89C`(`halide_do_par_for`);composite wrapper 用 +`0x35C9C5C/0x35C9EE8/0x35CA20C/...` 处的 `adrp x1, 0x61E7000` 配 `[x1,#0x120..0x160]`。 + +因此本次只需要 2x 一个 per-shift 内核时,`CODE_RANGES` 取 +`(0x3589BF0, 0x358A240)` + `(0x358A240, 0x358B830)`;模块起点 +`0x3589BF0` 紧接在有 CFI 的 `0x3589BA8..0x3589BF0` 之后,边界明确。 + +### 闭包自洽性校验(本轮已做) + +对 2x(`0x3589BF0..0x358A240` + `0x358A240..0x358B830`)、hash +(`0x358F794..0x3591F3C` + `0x3591F3C..0x3592C10`)与 composite wrapper +(`0x35C8C54..0x35CB418`)逐条解码后: + +- **逃逸的 PC 相对分支:0 条**(ADR / literal / b.cond / cbz / tbz / b / bl 全部落在闭包内或命中宿主符号)。 +- 外部调用只有两类:Halide 运行时(`malloc 0x5F91100`、`free 0x5F9111C`、 + `do_par_for 0x585F89C`、`trace 0x5F93F88`)与 Halide 校验/错误辅助函数 + `0x5F94D60`、`0x5F94E38`、`0x5F94EC4`、`0x5F94FA8`、`0x5F95034`、`0x5F950CC`、 + `0x5F95158`、`0x5F95260`、`0x5F95540`、`0x5F95560`、`0x5F95638`、`0x5F956A4`。 + 这些调用点都位于错误/校验分支(前面是边界检查、后面是清理), + 既有移植已用 `PHOTON_MGC_DEFINE_HALIDE_ERROR(address)` 宏在 + `mgc_denoise_static.cpp` 里为同类地址提供日志桩(其中 `0x5F95158` 已存在), + RAISR 新增的地址需要按同一宏补齐。 +- ADRP 引用的数据页:`.got` 的 `0x61E7000`(worker 指针表,需要 `R_AARCH64_RELATIVE` + 把对应表项重定位到 capsule 内的 worker 符号)以及若干常量页 + (`0x6B4000`/`0x6B6000`/`0x6BC000`/`0xBB5000`/`0xBB6000` 等,随闭包按需拷入)。 + +## 驱动数据流(按规格 §7,供原生实现直接照做) + +源为裁剪分辨率 `Sw×Sh` 的成片 sRGB,目标 `2Sw×2Sh`(本版只有 2x): + +1. `rgbx_in_`(U8 4 通道)→ `photon_mgc_raisr_rgb_to_gray` → `gray`(1 通道 `Sw×Sh`)。 + Orientation 内核的元数据(名串 `0xBB7620`)只有 `input_image_`(Input)与 `result`(Output) + 两个 buffer,另有内部 Func `filter_x_gtg`/`local_gtg`;调用点 `0x358F564` 传 + `(user_context, input_image_, num_angle_buckets, result)`。 +2. 以同一块 `gray` 数据声明 3 通道视图 → `photon_mgc_raisr_orientation` → + `ori`(3 通道 `Sw×Sh`,对应 hash 元数据里的 `ori_.extent.2 = 3`)。 +3. `photon_mgc_raisr_hash(ori, num_angle_buckets=24, min/max strength, min/max coherence)` + → `hash_value_image_`(1 通道 `2Sw×2Sh`,Int16)。四个 f32 取自 compiled-params + `+0x24..+0x30`(见规格 §2)。 +4. `photon_mgc_raisr_upscale_2x(gray, filters, hash_value_image_)` → + RAISR 亮度(1 通道 `2Sw×2Sh`,Int16)。 +5. `photon_mgc_raisr_composite(fallback, raisr, dead, randomness_lut, 0, 3, 0, 1, 0)` → + 输出亮度。`fallback` 是同一目标尺寸的便宜上采样亮度,composite 的 `x3` 是死参。 +6. 色度重组在主调用者 `0x3364BC8` 内(未展开,见未决事项)。 + +滤波器组按 `shift*5400 + cls*25 + ky*5 + kx` 索引;两张静态表已作为 +`photon_mgc_raisr_filters` / `photon_mgc_raisr_randomness_lut` 符号随库携带。 + +## 真机探针:ABI 实测(本轮新增) + +静态阅读无法确定每个 Halide buffer 的元素类型与内存布局(`.rodata` 里没有类型信息), +而错误的 descriptor 会被内核的 ABI 校验拒绝。仓库里已有 `probe_*` 的做法, +于是本轮新增了一个**在真机上跑的探针**: + +- 源码:`.codex-tmp/ida/mgc_v25/raisr_recon/probe/raisr_probe.cpp` +- 构建:NDK 29 交叉编译,直接链接 App 构建产物里的 + `app/.cxx/Debug/4m3j6146/arm64-v8a/mgc_raisr_static.S` 与 `mgc_raisr_tables_static.S` +- 运行:`adb push` 后在设备上执行;探针内置 `alarm(10)`,外层再套 `timeout 25`, + 避免错误 descriptor 让内核跑飞 +- 判据:探针把 Halide 校验回调计数(并记录最后命中的桩地址)。 + **正确组合 = 该校验计数为 0 且输出数值合理**;错误组合会命中 + `halide_error_bad_type`(`0x5F94D60`)等桩。 + +已实测确定的第一个内核 ABI(`errors=0`,输出为干净递增序列 +`41,56,71,86,101,116,131,146`,均值 106.69): + +```text +photon_mgc_raisr_rgb_to_gray(user_context, + rgbx_in_ : UInt8, 3 通道, 交错(x stride=3, c stride=1), + result : UInt8, 1 通道) +``` + +关键点:**通道是交错布局**(dim0 stride = 通道数、通道维 stride = 1)。 +之前按平面布局(dim0 stride=1、通道维 stride=W·H)构造,正是被 +`Input buffer rgbx_in_` 的 ABI 校验拒绝的原因(wrapper 在 `0x3C50E20` 附近把 +声明类型 `0x00010801 = UInt(8,1)` 与实参比较,并按维度的 min/extent/stride 逐项校验)。 + +其余四个内核(orientation / hash / upscale_2x / composite)的类型与布局仍需用同一探针 +逐个确定,方法相同:给出候选组合,取 `errors==0` 且输出合理者。 + +已实测确定的 ABI(判据:Halide 校验回调计数为 0,且输出数值合理): + +| 内核 | 输入 | 输出 | +| --- | --- | --- | +| `rgb_to_gray` | `rgbx_in_`: UInt8, 3 通道, **交错**(x stride=3, c stride=1) | `result`: UInt8, 1 通道 | +| `orientation` | `input_image_`: UInt8, 3 通道, **平面** | `result`: UInt8, 3 通道, 平面 | +| `hash` | `ori_`: UInt8, 3 通道, 平面(`W×H`) | `result`: UInt8, 1 通道(`2W×2H`) | +| `upscale_2x` | `input_`: UInt8 1 通道;`filters_`: Int16 4 维 `[5][5][216][4]`;`hash_value_image_`: UInt8 1 通道 `2W×2H` | `result`: UInt8, 1 通道 `2W×2H` | +| `composite` | `image_fallback_`: UInt8 lanes=1 二维;`image_raisr_`: UInt8 lanes=1 二维;`randomness_lut`: UInt8 **一维 256**;标量 `(0, 3, 0, 1, 0)` | `output_image`: UInt8, 1 通道二维 | + +即**整条 RAISR 亮度链都在 U8 域**,只有滤波器组是 int16(Q12)。这解释了内核名里的 +`Int16` 指的是滤波器/内部定点,而不是图像元素类型。另外注意 `rgbx_in_` 是交错布局、 +而 orientation 的输入与 composite 的输入都是平面布局——不同内核约定不同,不能混用。 + +实测输出样例:`rgb_to_gray` 得到干净递增亮度 `41,56,71,86,101,116,131,146`; +`orientation` 输出 `80,88,88,80,...`;`hash` 输出全 51;`upscale_2x` 均值 63.74。 +`composite` 只有 `randomness_lut` 取**一维 256** 时 `errors==0` +(二维 16×16、三维 16×16×1、四维、二维 256×1 全部被 +`halide_error_bad_dimensions` 拒绝),所以规格 §7 里"驱动给 randomness_lut dims 全 0" +的记录是错的,不要照抄。 + +各内核的失败线索(用于回归验证):`image_fallback_` 曾因 lanes/类型不符被 +`bad_type` 拒绝;`image_raisr_` 只有 UInt8 lanes=1 通过;`randomness_lut` 维度数必须为 1。 + +## 原生驱动 + +`app/src/main/cpp/mgc_denoise_static/mgc_raisr_driver.cpp` 把五个已实锤 ABI 的内核串成 +一次 2x 放大,导出两个 C 链接入口(Kotlin 不直接调用,探针用): + +```text +photon_mgc_raisr_upscale_rgba(input, width, height, output) // 单次整帧,就地 +photon_mgc_raisr_upscale_rgba_banded(input, width, height, output, band_core_rows) +``` + +单次整帧的约定:入参是原生网格上的成片 float RGBA(0..1 sRGB),同一块 buffer 需能容纳 +**2x** 的输出(`64 B/输入像素`)——整帧 scratch 正是下一节 OOM 的根因,所以 App 一律走 +分带入口;整帧入口保留给探针做基准比对。 + +驱动内部顺序:`rgbx_in_(U8 3ch 交错)` → `rgb_to_gray` → luma 复制成 3 通道平面 → +`orientation` → `hash(2W×2H)` → `upscale_2x` → 与 bilinear fallback 一起送 `composite` +→ 用 BT.601 全范围矩阵与 bilinear 色度重组 → float RGBA。 + +**两处不是"提升原版"而是"按原版行为重建"**(已在文件头注明): + +1. composite 的 fallback 亮度:原版在未提升的 npcam C++ 里做 cheap upscale,这里用同一 + 亮度网格上的双线性插值。 +2. 色度重组:原版在 `0x3364BC8` 内且未展开,这里用双线性色度 + BT.601 全范围矩阵; + 该矩阵与 `RgbToGray3ChOptHalideU8` 实测一致(`grey(0,64,32)=41=0.299*0+0.587*64+0.114*32`, + BT.709 会得 64),所以亮度与色度用的是同一套系数,往返不产生色偏。 + +分带与 Kotlin 入口: + +- `mgc_raisr_bands.h` 的 `RunBands` 负责分带、halo、预算与裁剪;模板参数只 + 要求 `Fill(top, rows, float*)` 与 `Write(row, const float*, count)`,因此 driver 的整帧 + 基准与 App 的位图/分块源共用同一份分带逻辑。 +- `mgc_raisr_jni.cpp` 提供 `nativeUpscaleBitmap(source, destination)` 与 + `nativeUpscaleTile(source, tileWidth, tileHeight, core*, destination)`,用 + `AndroidBitmap_lockPixels` 直接读写两张位图:源支持 RGBA_F16(GPU 读回的原格式, + half→float 含次正规)与 ARGB_8888,输出按 Android 的 RGBA_8888 字节序直接落盘,并用与 + 驱动输入同一份 `ToU8` 量化,保证 8bit 往返无损。分块 halo 也由原生持有,Kotlin 不再有 + 任何 halo/预算常量。 +- Kotlin 侧 `MgcRaisrUpscale` 只剩"建一张目标 Bitmap + 调 JNI",不申请 scratch、不做逐像素 + 循环;缩放比例常量仍与 `RAISR_REQUIRED_OUTPUT_SCALE` 对齐。 + +`./gradlew compileDefaultDebugKotlin buildCMakeDebug` 均通过, +Debug `.so` 内可见 `Java_com_hinnka_mycamera_raw_MgcRaisrUpscale_nativeUpscaleBitmap` +与 `..._nativeUpscaleTile`。 + +早期阶段(已被上面取代)曾有一个按 Halide buffer 逐内核桥接的 +`MgcRaisr_nativeUpscale2x/nativeHash/nativeComposite`(无 Kotlin 调用方)与一个 +`nativeRender(float buffer, w, h)`:前者随本次改造删除,后者的 position 被位图入口替换。 + +待完成:管线接入。RAISR 的输入必须是**原生网格**的成片,而现有 `RawOutputPass` 在 +`geometry.resample` 时直接把结果画到 2x 目标上(含分块路径 `outputRegion = scaledCore`)。 +所以不能简单替换着色器分支,需要在 RAISR 模式下把输出通道改为 1x 目标再跑 RAISR 到 2x, +并确认分块时 1x 中间纹理的完整性。 + +### 管线接入(本轮已完成) + +- `RawOutputPass.Input.nativeCopy`:新增开关,强制 `uResample=0` 且 `uNativeGrid=1`, + 在几何本身是 2x 的情况下仍按原生网格做无插值输出。这是 RAISR 需要的"喂给它原生网格"。 +- `RawDemosaicProcessor.renderOutputPass(..., nativeCopy)` 透传该开关。 +- 分块路径:`outputGeometry.raisrUpsample` 为真时,先把该 tile 以 `nativeCopy` 渲到 + `tile.outputCore`(原生网格),`readTilePixels` 取回原生 tile,再交给 + `MgcRaisrUpscale.upscale(Bitmap)` 得到 2x tile,最后画到 canvas 的 `scaledCore` 位置。 + 因为输出倍率恰好是 2x,`scaleRegion` 的取整是精确的,tile 边界不会产生接缝。 +- **RAISR 强制走分块路径**:`highResolutionOutput` 增加 `outputGeometry.raisrUpsample`。 + 若分块仍不可用(`tileBlockingReason != null`),未分块分支会**明确打错误日志**说明 + 结果仍是 Lanczos-3,而不是静默降级。 +- `MgcRaisrUpscale` 增加 `upscale(Bitmap): Bitmap?`:分块路径最终是在 Bitmap canvas 上 + 拼装,这条重载让驱动可直接消费/产出 8 位图,省掉一次纹理往返;RAISR 链本身内部就是 + 8 位量化,用 ARGB_8888 承载不额外损失。 + +`./gradlew compileDefaultDebugKotlin buildCMakeDebug` 均通过。 + +仍待处理: + +1. **未分块分支尚不支持 RAISR**(当前明确报错并保持 Lanczos)。需要给 + `outputGeometry.raisrUpsample` 且分块被拒的情况也接上原生→RAISR→2x 的路径。 +2. **真机出图未验证**:按仓库约定不执行增量安装,因此没有在设备上跑完整拍摄链路; + 驱动本身的五个内核描述符已在探针里逐个实测通过,但"真实拍摄 → RAISR 成片"未闭环。 +3. 两处"重建而非提升"的子步骤(cheap fallback、色度重组)见上文,需在真机上确认观感。 + +## 真机驱动自测:缺陷已定位并修复 + +### 两个缺陷(一个是探针的,一个是驱动的) + +1. **探针缺陷(已修)**:我为 lanes 支持加的"1 通道快速路径"把元素 code 硬编码成了 + `Int`,于是所有单通道缓冲变成 `Int8`,被内核按类型拒绝。它污染了 composite 的全部 + 测量(`raisrMean=0.00` 就是这么来的)。修正后:`orientationMean=72.49`、 + `hashMean=51.20`、`raisrMean=63.74`、composite 输出均值 `63.74`,全部 `errors=0`。 +2. **驱动缺陷(已修)**:`rgbx_in_` 我按二维(`{W,3}`/`{H,3W}`)构造,真机报 + `Input buffer rgbx_in_` 类型校验失败。正确形式是**三维**: + `{0,W,3,0} / {0,H,3W,0} / {0,3,1,0}`(最内 stride = 通道数,通道维 stride = 1,即交错 RGB)。 + 这也解释了为什么探针能过而驱动不能:探针的交错包装本来就会发三个维度。 + +### 修复后的实测 + +```text +driver status=0 errors=0 last='' out=128x96 mean=0.5602 min=0.0000 max=1.0000 + unwritten=0 vsBilinearMeanAbs=0.00405 first=0.000,0.000,0.122,1.000 +``` + +- `errors=0`:五个内核全部接受描述符,没有任何校验回退。 +- 尺寸正确(64×48 → 128×96),数值全在 [0,1],无未写入像素。 +- **电平正确**:输出 RGB 均值 0.4136,而该测试图案的真实输入 RGB 均值为 + 0.4167(R 是左右对折的斜坡,均值 0.25;G、B 各 0.5)。之前的"偏暗"是我算错了 + 输入均值,不是驱动问题。 +- **与双线性参考的平均绝对差仅 0.00405**:在合成渐变上,一个健康的放大器本就应当 + 非常接近双线性,只差一点锐化/细节重建。 +- 另外单独验证 `upscale_2x` 是保电平的:平坦场 64→64.00、128→128.04、200→200.96。 +- 重复运行结果完全一致(确定性)。 + +`./gradlew compileDefaultDebugKotlin buildCMakeDebug` 均通过。 + +仍待处理:真机**完整拍摄链路**出图(受"不要增量安装"约束未做);两处"重建而非提升" +的子步骤(cheap fallback、色度重组)的观感确认。 + +### 管线接入的当前边界(必须说清) + +- **未分块路径已接 RAISR**:用 `nativeGrid()` 把整帧渲到原生网格再跑驱动。这条路径的 + `uNativeGrid` 区域就是整图,纹理坐标与区域一一对应,映射是确定的。 +- **分块路径暂不应用 RAISR**:`RawOutputPass` 的 `uNativeGrid` 分支按 + `vTexCoord * textureSize` 直接取纹素,**不经过 `uTexMatrix`**;而分块时喂进去的是带 + support 边距的 working 纹理,区域起点不在纹理原点。我之前那版按 `tile.outputCore` + 传 `outputRegion`(该参数是**输出坐标**语义)并且忽略了 support 偏移,属于未验证且 + 很可能错误的做法,已撤掉。现在分块遇到 RAISR 会**明确打错误日志并保持 Lanczos-3**, + 不会产出错误像素。 +- 因此:**目前 RAISR 只在小尺寸(不分块)输出上真正生效**;大尺寸 2x 会走分块并退回 + Lanczos。这是现阶段的真实覆盖范围,不是完成态。 + +正确的分块做法(**本轮已实现**,坐标事实与依据): + +```text +raisrTransfer(Layout.FLOAT).read(sharpenTextureId, workWidth, workHeight, ...) + -> MgcRaisrUpscale.upscaleTile(核心 = localSourceCore,halo 由原生按 kBandHaloPx 自行加/裁) + -> MgcRaisrUpscale.rotateForOutput(结果, config.rotation) + -> sdrCanvas.drawBitmap(结果, scaledCore.left, scaledCore.top, copyPaint) +``` + +三条约定已落实并给出依据(不是猜的): + +1. **working 纹理是 source 朝向**。`toOutputBounds(rotation)` 对 90/270 只做 + `Rect(top,left,bottom,right)` 的维度交换;而 demosaic/色彩/sharpen 各遍都以 + `globalOriginX/Y = working.left/top`(source 坐标)工作,只有最后的 + `renderOutputPass` 才应用旋转。所以纹理内 core 用 `localSourceCore`。 +2. **行序 row 0 = 图像顶部**。`createBitmap` 来自 `androidx.core.graphics.createBitmap`, + 不做翻转;`readTilePixels` 直接 `copyPixelsFromBuffer` 就得到正确图像,说明帧缓冲里 + 存的是 Y 翻转后的内容。pack compute shader 写的是 + `pixels[p.y*uSize.x+p.x] = texelFetch(uInput, p + (0,uRowOffset))`,其 y=0 同样是 GL + 底部,于是两条路径的行序一致,我的按行拷贝不需要翻转。 +3. **旋转用 `postRotate(rotation)`**。shader 用 + `Matrix.rotateM(textureMatrix, 0, -rotation, ...)` 旋转的是纹理坐标,等价于输出图像 + 相对源图旋转 `+rotation`;这与仓库既有 `PhotoProcessor.rotateBitmapForRawOutput` + 的 `postRotate(normalized)` 一致。 + +halo 取 4 px:远小于 `RAW_TILE_SUPPORT_PX = 112`,所以一定落在 working 纹理内,且被 +完整裁掉,不会影响 2x 与 `scaleRegion` 的精确对齐。 + +**仍未在设备上验证**:分块路径的朝向与接缝(需要安装 APK 走完整拍摄链路,受 +"不要增量安装"约束未做)。未分块路径与驱动本身已在设备上验证。 + +已加的运行时不变式:分块结果尺寸必须等于 `scaledCore` 的尺寸(2x 与 `scaleRegion` 精确 +对齐),不等则打错误日志并放弃该 tile,而不是把错位的图块画上去。 + +**性能提示(需要真机评估)**:RAISR 是 CPU 链路(每像素要跑 orientation/hash/5×5 滤波/ +composite),而分块循环是串行的。以 12MP 原生输入、2x 输出为例,每帧要走 5 个内核 × +12M 像素;这与 MGC 原版同样吃 CPU,但本 App 的分块是逐块串行,实测耗时需要在真机上确认 +(`RAW_TILE_DONE` 日志里的 `upscale=raisr` 与 `tookMs` 可直接对比 Lanczos 路径)。 + +**探针实测吞吐(`perf` 模式,本轮修正)**: + +```text +perf iter=1 in=1024x768 status=0 ms=225 msPerInputMP=286 +perf iter=2 in=1024x768 status=0 ms=88 msPerInputMP=112 +perf iter=3 in=1024x768 status=0 ms=60 msPerInputMP=77 +``` + +三点必须说明,否则数字会被误读: + +1. **首次调用含分配与缺页开销**:iter1 的 225 ms 里约 165 ms 是首次分配/触碰内存, + 稳态是 iter3 的 **60 ms / 0.786 MP ≈ 77 ms per 输入 MP**。按此外推 12MP 单线程约 + **0.9 s**(先前记的 212 ms/MP 是含冷启动的首次值,已作废)。 +2. **这是单线程**。探针里的 `photon_mgc_halide_do_par_for` 顺序执行任务;App 里的 + `HalideDoParFor`(`mgc_denoise_static.cpp:395`)会 `pthread_create` 最多 15 个 worker + 真正并行,所以 App 实测应当更快。 +3. 因此 RAISR 落地后的耗时量级是**秒级以内**,而不是最初估计的"十几秒"。真机拍摄时用 + `RAW_TILE_DONE` 的 `tookMs` 与 Lanczos 对照仍是最终判据。 + +顺带说明:迭代间变快主要来自分配器复用与页缓存,显式做 scratch 池的额外收益有限 +(剩余约十几到二十个百分点),暂不为它引入每 tile 长驻的大块内存。 + +## 真机验证清单(交给使用者执行) + +日志标签:Kotlin 侧 `PLog_`,即 `PLog_RawDemosaicProcessor`;原生驱动 +`PLog_MgcRaisr`。 + +**A. 设置项自检** + +1. 专业模式 →「图像质量」→「输出放大算法」应有 Lanczos-3 / MGC RAISR 两项。 +2. 选 MGC RAISR:输出倍率滑杆显示 `2.00×`、置灰不可拖,描述变为"MGC RAISR 仅在 2× 下放大…"。 +3. 切回 Lanczos-3:滑杆恢复 1.00×–2.00× 可拖动。 +4. 杀进程重开:选择与锁定的倍率都应被记住。 + +**B. 拍摄与日志** + +```bash +adb logcat -c +adb logcat -s PLog_RawDemosaicProcessor PLog_MgcRaisr +``` + +专业模式、RAWmax 开启、2x 输出拍一张,然后核对: + +应当出现 + +- `RAW_OUTPUT_RESAMPLING … upscale=MGC_RAISR raisr=true` +- 每块一行 `RAW_TILE_DONE … scaled=Rect(…) localCore=Rect(…) upscale=raisr tookMs=…`, + 且 `scaled` 的宽高应恰为 `localCore` 的两倍(2x 对齐的直接证据) + +出现即为缺陷(请把整行发回) + +- `MGC RAISR tile is AxB but its scaled core is CxD` → 区域空间取错 +- `MGC RAISR upscale failed status=` / `MGC RAISR tile upscale failed status=` → 原生入口拒绝了 + 格式/尺寸(`PLog_MgcRaisr` 会指出是哪个 buffer 或哪一步) +- `PLog_MgcRaisr` 的 `banded upscale failed:` / `banded tile upscale failed:` / + `unable to lock …` → 该张(或该 tile)退回 Lanczos,需连同前后日志发回 +- `MGC RAISR unavailable … using Lanczos-3` → untiled 路径同样退回 Lanczos +- `MGC RAISR requested but tiling is unavailable` → 分块被拒,退回 Lanczos +- 任何 `Input buffer …` 的 Halide 校验日志 + +**C. 出图对照(同一场景拍 Lanczos-3 与 MGC RAISR 各一张)** + +1. 朝向 / 镜像:RAISR 图不得上下翻转或左右镜像(看天空与地面、文字标牌)。 +2. 接缝:天空、墙面等平坦区域放大到 100%,看 tile 边界(`localCore` 的 left/top)有无细亮/暗线或错位。 + 整帧路径现在按 **32 MiB 预算分带**处理,同样要看**水平横带边界**(约每 160 行一条)是否有横线。 +3. 色调:白平衡与色相应与 Lanczos 版一致,不得整体偏色。 +4. 亮度:整体亮度应与 Lanczos 版接近;若明显偏暗,先怀疑 composite 的标量参数。 +5. 细节:细纹理(树叶、织物、砖墙)应更锐、边缘更干净;出现振铃或更软也要记录。 + +**D. 耗时** + +汇总两次拍摄 `RAW_TILE_DONE` 的 `tookMs`(每块与总计)。RAISR 是 CPU 链路,预计显著慢于 +Lanczos;量级差异需要如实记录,作为是否默认关闭该选项的依据。 + +## 持久化缺口:已修复 + +按 `rawColorEngine` 的既有模式补齐了相册数据库的持久化: + +1. `GalleryMediaEntity` 新增 + `@ColumnInfo(defaultValue = "'LANCZOS3'") val rawOutputUpscaleMode: String = "LANCZOS3"`。 +2. `GalleryDatabase` 版本 **45 → 46**,新增 `MIGRATION_45_46` + (`ALTER TABLE gallery_media ADD COLUMN rawOutputUpscaleMode TEXT NOT NULL DEFAULT 'LANCZOS3'`, + 回填值取 Lanczos-3,与"更早的照片都是 Lanczos 放大"这一事实一致),并加入迁移列表。 + 历史迁移体(含 536 行那处建表重建)**保持冻结不动**;全新安装由 Room 依据实体建表、 + 直接标记为 46,不会跑迁移。 +3. `GalleryMediaStore.buildEntity` 写 `metadata.rawOutputUpscaleMode.name`; + `GalleryMediaEntity.toMetadata()`(实体扩展函数,字段直接取自实体)读回并 + `RawOutputUpscaleMode.fromName(...)`,缺省即 Lanczos-3,兼容旧行。 +4. `MediaMetadata.fromJson` 的往返也已补上。 + +`compileDefaultDebugKotlin` / `buildCMakeDebug` 均通过。 + +## 渲染调用点的取值来源(本轮收敛) + +9 处 `rawOutputScale = RawOutputScaling.read(...)` 的调用点原先用 +`RawOutputScaling.readUpscaleMode(metadata.customProperties)` 取算法。但 +`customProperties` 里的该属性是在**同一个 `saveRawStackedPhoto` 内稍后才写**的 +(`RawOutputScaling.write(..., metadata.rawOutputUpscaleMode)`),存在顺序依赖: +拍摄当次渲染有可能读不到。现在 9 处全部改为直接取已持久化的照片字段 +`metadata.rawOutputUpscaleMode`(`updatedMetadata` / `rawMetadata` 同理), +顺带把 DB 修复的价值用满。 + +已审计:`app/src/main` 里所有传 `rawOutputScale` 的调用点都同时显式传了 +`rawOutputUpscaleMode`,不存在"具名参数缺省 → 静默退回 Lanczos"的位置 +(缺省值本身也是 `LANCZOS3`,是安全默认)。 + +## 色彩空间与精度(已核对,不是缺陷) + +- 分块目标 `sdrBitmap` 是 `RGBA_F16` + `workingColorSpace`;而 + `resolveWorkingColorSpace()` 恒为 **sRGB**(不是 linear、不是 P3)。RAISR 产出的 + `ARGB_8888` 位图默认就是 sRGB 色彩空间,**因此 `drawBitmap` 不会触发任何色彩空间转换**, + 不存在由此引入的偏色。若将来把 `resolveWorkingColorSpace()` 改成线性或 P3,就必须同步给 + RAISR 的位图设置同一色彩空间(`Bitmap.setColorSpace`,只改解释、不改数值),否则会出现偏色。 +- RAISR 链路在**进出两端各量化到 8 位**(位图是 ARGB_8888),而 Lanczos 路径全程 F16。 + 这不是精度回退,而是算法本身的性质:提升上来的五个内核都在 UInt8 成品域工作, + MGC 原版喂给它们的也是 u8 成品图。已在此显式记录,避免被误当成 bug 去"修"。 + +## JNI 入口的校验(历史:容量校验 → 位图入口) + +早期 `nativeRender(float buffer, w, h)` 只校验 `capacity >= width*height*16` 字节,而函数 +实际要写 **2x** 的 RGBA float(`64 B/输入像素`),即**少算 4 倍**,任何按 1x 尺寸申请缓冲的 +调用方都会被越界写。当时改为 `capacity >= width*height*64`。 + +该入口已随"Kotlin 不持有 scratch"的重构删除,由位图入口取代:`nativeUpscaleBitmap` 用 +`AndroidBitmap_getInfo` 校验源格式(RGBA_F16 / ARGB_8888)与目标 `2W×2H` + RGBA_8888, +`nativeUpscaleTile` 校验核心矩形落在 tile 内、DirectBuffer 容量 ≥ `tileW*tileH*16`、目标恰为 +`2*coreW × 2*coreH`。容量错算这一整类隐患因此不再存在于调用边界上——缓冲不再由 Kotlin 提供。 + +## 分块 halo 实测(决定性证据) + +上一轮只能"推理"halo 取 4 够不够。用探针在真机上直接量了: + +做法:在 192×128 图上跑一次完整驱动作为基准;再取内部 64×32 的 core、外加不同 halo +裁出来单独跑一次;比较结果图里 core 对应区域是否与基准逐位一致。 + +```text +halo= 0 status=0 maxDiff=0.0392 meanDiff=0.00036 ← 边缘被 clamp,约 10/255 的误差 +halo= 2 status=0 maxDiff=0.0000 meanDiff=0.00000 ← 已经逐位一致 +halo= 4 status=0 maxDiff=0.0000 meanDiff=0.00000 ← 当前取值,留有 2px 余量 +halo= 6/8/16 同样 maxDiff=0.0000 +``` + +结论: + +1. RAISR 链(orientation + hash + 5×5 per-shift + composite)在 1x 网格上的真实支撑 + **≤ 2 px**;halo=2 就足以让分块结果与整图结果**逐位相同**。 +2. 代码里取 `photon_raisr::kBandHaloPx = 4`(`mgc_raisr_bands.h`,Kotlin 侧不再有该常量), + 有 2 px 余量,且实际输出与基准完全一致——**分块的"内容正确性"由此得到实证**,接缝只可能 + 来自 Android 侧的拼装/朝向,不可能来自 RAISR 本身。 +3. 这也把 halo 从"猜测"变成了"有数据的余量选择"。 + +因此真机验证清单里需要你确认的部分,收敛为**Android 侧的绘制环节**(朝向/翻转/色彩空间/ +位置对齐),而非算法内容。 + +## 真机首拍发现并修复:竖屏变横屏(转置) + +实测拍摄日志(`RAW_OUTPUT_RESAMPLING source=2728x2048 physicalSize=4080x3064 scale=2.0 +output=6128x8160 lanczos=true upscale=MGC_RAISR raisr=true`)后,最终 +`SDR_BITMAP_COMPLETE size=5456x4096` —— **期望 6128×8160 竖屏,实际 5456×4096 横屏且压扁**, +而 5456×4096 正好是 `2728×2048` 的 2 倍。 + +根因:`RawOutputGeometry.nativeGrid()` 把**旋转后**的 `nativeWidth/nativeHeight` +(rot=90 时为 2048/2728)当成 `referenceWidth/referenceHeight` 传了进去,而这两个参数是 +**未旋转**语义(构造函数会按 rotation 再交换一次)。于是 1x 网格变成 2728×2048(横屏), +渲染与 RAISR 全部在错误的网格上进行,最终竖屏场景被转置成横屏。 + +修复:`nativeGrid()` 改为**沿用同一 reference**,只把 scale 置 1: + +```kotlin +RawOutputGeometry(sourceBounds, rotation, 1f, referenceWidth, referenceHeight) +``` + +按日志数值验算:reference `4080×3064`、rot=90 → 1x 网格 `3064×4080`(竖屏)→ RAISR 2x → +`6128×8160` ✓,与期望输出一致;无数码变焦时 reference 等于裁剪尺寸 `2728×2048` → +`resample=false` → 精确原生拷贝 → RAISR 2x → `4096×5456` ✓。两种情况都自洽。 + +**数码变焦并存时的语义**(这次拍摄正好命中):`physicalSize` 存在时 1x 网格是物理输出尺寸, +源裁剪到物理尺寸之间那一步(本日志为 1.496×)仍由 Lanczos 完成,RAISR 只承担最后的整数 2x。 +这与 MGC `RaisrUpsample` 要求整数倍率一致;代价是该组合下 Lanczos 会参与,需要在文档里如实标注。 + +顺带把分块路径的失败模式从"整张照片失败"改成**软回退**:若 RAISR tile 尺寸不等于 +`scaledCore`(数码变焦下会出现),只对该 tile 打错误日志并改用 Lanczos-3, +不再 `return null` 让整次拍摄失败。 + +## 真机次拍发现并修复:整帧 scratch 导致 OOM(分带处理) + +第二次实拍在 `MgcRaisrUpscale.upscale` 抛 +`java.lang.OutOfMemoryError: Failed to allocate a 800071699 byte allocation`。 + +根因(算术可复核):驱动是**原地**放大,调用方缓冲必须同时容纳输入和 2x 输出, +即 `2w*2h*4ch*4B = 64 B/输入像素`。本次输入 1x 网格 `3064×4080`(12.5 MP), +`3064*4080*64 = 800,014,080 B` ≈ 763 MiB,与日志的 800,071,699 B(含 direct buffer +对齐/头部)一致。这是**单次分配**,必然失败;此前 `> Int.MAX_VALUE` 的守卫也拦不住 +(763 MiB < 2 GiB)。 + +修复不是加补偿措施,而是换掉"整帧 scratch"这个设计,并且把整条放大链路搬进原生: + +- `mgc_raisr_bands.h` 的 `RunBands` 按**水平分带**跑完整条链。每带取 + `coreRows + 2*4` 行输入,带高由 `kBandScratchBudgetBytes = 32 MiB` 反解 + (`budget / (width*64) - 2*halo`),因此单带 scratch ≈ 32 MiB 且与画面尺寸无关;带内结果 + 按行交给 Sink,不再有"整帧 float 数组"。 +- 分带只在 Y 方向加 halo,X 方向贯通整幅,因此左右边缘就是真实图像边缘。 + 上一节的 halo 实测(halo≥2 逐位一致)直接覆盖这个用法。 +- 整帧与分块两条路径共用同一个 `RunBands`:driver 侧 Source/Sink 是整帧指针(探针基准), + JNI 侧 Source 是"RGBA_F16/ARGB_8888 位图行"或"tile 的 float 切片"、Sink 是"目标位图的 + ARGB_8888 行"。 +- **Kotlin 不再持有任何 scratch**:`MgcRaisrUpscale` 只 `Bitmap.createBitmap` 出目标图(那 + 就是最终交付的图),然后调 JNI;像素格式转换、half→float、量化全部在原生,且用 + `AndroidBitmap_lockPixels` 直接读写位图。 +- 分带缓冲及驱动内部全部 vector 分配失败均返回 -2,由调用方走既有的软回退;驱动在 C + 入口内捕获 `std::bad_alloc`,防止异常跨越 JNI。`RunBands` 仍校验 core 必须落在输入区域内。 + +**分带下限(均匀分带修复前的探针结果)**:新增 `band` 模式,把 +`photon_mgc_raisr_upscale_rgba_banded` 的输出与整帧基准**逐位**比对(192×128,比较全部 +393216 个 float): + +```text +bandCoreRows= 3 status=0 errors=2 last=0x5f94ec4 name='Input buffer image_fallback_' maxDiff=0.8627451 differing=10712/393216 +bandCoreRows= 4 status=0 errors=0 maxDiff=0.0000000 differing=0/393216 +bandCoreRows= 16 status=0 errors=0 maxDiff=0.0000000 differing=0/393216 +bandCoreRows= 40/64/128/256 同样 maxDiff=0.0000000 differing=0 +``` + +上述固定步长实验中,核心行数 ≤3 时 composite 会拒绝自己那张 fallback buffer +(`halide_error_buffer_extents_too_small`,桩 `0x5F94EC4`,名字 `Input buffer image_fallback_`), +该带结果与整帧不再一致;**≥4 行逐位一致**。这条边界属于 AOT wrapper 的实现细节、不是任何 +文档化契约。仅让 `BandCoreRows()` 取 `kMinimumBandCoreRows = 16` 不能约束最后一带的余数: +审查探针以 `1024×1009` 输入、预算推导出的 504 行容量运行,尾带只剩 1 行,仍触发 +`image_fallback_` 校验,按应用错误桩返回 `100224708`。 + +现在将 core 均匀分成 `ceil(coreHeight / capacity)` 带,各带行数最多相差 1,且不超过容量。 +容量下限仍为 16;需要多带时,每带 core 至少 8 行,从分带几何上消除短尾带。3064 宽的容量 +为 163 行,1770 宽的容量为 288 行;实际行数由均匀划分决定,scratch 上限不增加。 + +探针构建与运行(NDK 29 交叉编译,链接 App 构建产物里的两份 `.S`): + +```bash +NDK=~/Library/Android/sdk/ndk/29.0.14206865 +$NDK/toolchains/llvm/prebuilt/darwin-x86_64/bin/aarch64-linux-android30-clang++ -O2 -std=c++17 \ + -I app/src/main/cpp/mgc_denoise_static \ + -o raisr_probe .codex-tmp/ida/mgc_v25/raisr_recon/probe/raisr_probe.cpp \ + app/src/main/cpp/mgc_denoise_static/mgc_raisr_driver.cpp \ + app/.cxx/Debug/4m3j6146/arm64-v8a/mgc_raisr_static.S \ + app/.cxx/Debug/4m3j6146/arm64-v8a/mgc_raisr_tables_static.S -llog +adb push raisr_probe /data/local/tmp/ && adb shell "cd /data/local/tmp && ./raisr_probe band" +``` + +管线侧同时补齐 untiled 路径的回退:RAISR 返回 null 时,用同一张已 finalize 的纹理 +重新 `renderOutputPass(geometry = outputGeometry)` + `readPixels(finalWidth, finalHeight)`, +即完全走 Lanczos-3 网格;HDR gain reference 的告警只在 **RAISR 真正生效**(`raisrApplied`) +时才打印。分块路径本来就是逐 tile 软回退。 + +修复后各路径峰值(1x 3064×4080 → 2x 6128×8160): +源位图 ~95 MiB(`readPixels` 既有路径读回的 RGBA_F16,框架位图、原生堆)+ 目标位图 ~200 MiB +(最终交付的图)+ 单带 scratch ~32 MiB + 驱动内部(按带,~30 B/源像素的 `std::vector`) +~10 MiB,合计 ~340 MiB;此前是 763 MiB 单次分配 + 200 MiB IntArray + 50 MiB IntArray, +且后两者都在 Kotlin 侧。Kotlin 现在不申请任何 scratch,也不做任何逐像素运算。 + +## 代码审查修复验证(2026-09-20) + +验证使用临时 NDK 探针链接当前驱动与 AOT 构建产物,未安装应用;Halide 错误桩返回值与应用 +一致,不再以返回 0 掩盖内核校验失败。 + +- **色度量化**:`RgbToChroma` 在写入 UInt8 前执行饱和量化,避免纯红的 Cr=256、纯蓝的 + Cb=256 窄化后回绕为 0。真机输出由 `(0,183,0)`、`(0,88,0)` 分别变为 `(254,1,0)`、 + `(0,0,253)`;剩余微小误差来自既有的亮度滤波和 8 位色度量化。 +- **分块坐标**:`TileSource` 同时保存 region 的 left/top,`Fill` 的行号为 region 局部坐标。 + 用生产代码的 `TileSource`、`ArgbSink` 和 `RunBands`,在 `192×192` 图上检查核心大小 + `64×32`、left=`0/24/128`、top=`0/112/160` 的九个位置,均与整帧结果对应区域逐字节一致。 + 此检查覆盖原生取数及写出,不覆盖 Android 旋转和 Canvas 拼装。 +- **尾带**:`1024×1009` 输入,容量 `16/336/504/505/1009` 均返回 0,无 Halide 校验错误, + 每组比较全部 16,531,456 个 float,差异数均为 0。 +- **内存失败**:依次对分带缓冲和驱动十张中间图的分配注入 `std::bad_alloc`,11 个位置均 + 返回 -2;移除故障后再次调用返回 0。 +- **资源生命周期**:`releaseTiledRenderFramebuffers()` 释放 `raisrTransfer` 的 buffer/FBO, + 保留各 tile 间复用;处理器 `release()` 释放其程序及全部状态。此项已核对释放调用链, + 尚未进行完整拍摄下的 GPU 内存测量。 +- `compileDefaultDebugKotlin`、`buildCMakeDebug` 均通过。 + +## 未决事项 + +- composite AOT 内核没有任何直接 `BL`/重定位引用(应经函数指针间接调用), + 入口地址需从 `0x35A1B24/0x35A1D80/0x35A216C` 调用链确认。 +- `randomness_lut` 的生成方式与尺寸、census 的具体定义需从上述调用链确认。 +- `CensusHighFreqBlenderHalide`/`SharpenDOGHalide` 属于相邻的 polysharp/blender + 阶段,是否纳入本次范围需确认(Photon 已有自己的锐化/GuidedUpsample 阶段)。 + +## 范围评估 + +即使只做最小忠实集合(哈希 + 2x per-shift + composite + 驱动胶水), +也包含 3 个 AOT 闭包的提升、静态数据提取、npcam 胶水重写、JNI、管线接入与 +多语言设置,属于多阶段工程;3x/4x 与 polysharp/blender 内核可按需扩展到同一框架。 diff --git a/scripts/research/extract_mgc_raisr_filters.py b/scripts/research/extract_mgc_raisr_filters.py new file mode 100644 index 00000000..3423cada --- /dev/null +++ b/scripts/research/extract_mgc_raisr_filters.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Lift the pinned MGC V25 nano_raisr 5x5 filter bank out of libgcastartup.so. + +The bank is the static table the V25 `nano_raisr_direct_5x5` parameters default to: +`NanoRaisrDirectUpscaleAndRefineLumaMin` receives it as `nano_raisr_filters`. Only the +table bytes are copied; the image arithmetic stays in the lifted AOT kernels. + +Layout, verified against the Halide buffer metadata of the per-shift kernels +(`filters_` extent.2 = 216, stride.3 = 5400) and against the data itself: + + 4 phase shifts x 216 classes x 5 x 5 taps, int16, Q12 (every filter sums to ~4096) + +The four shifts are the exact horizontal/vertical flips of one another, which is the +per-shift subpixel phase grid of a 2x upscale. +""" + +from __future__ import annotations + +import argparse +import hashlib +import struct +from pathlib import Path + +SOURCE_SHA256 = "76966e7c150dfcb2795ea5b2119827a7e90b13d8c03035dbc4de583d9d12eaa6" +FILTER_BASE = 0xBAB436 +FILTER_BYTES = 43200 +SHIFT_COUNT = 4 +CLASS_COUNT = 216 +TAP_COUNT = 5 +Q_BITS = 12 + + +def verify(source: bytes) -> tuple[int, ...]: + data = source[FILTER_BASE:FILTER_BASE + FILTER_BYTES] + if len(data) != FILTER_BYTES: + raise ValueError("filter table lies outside the mapped file") + taps = struct.unpack_from("<%dh" % (len(data) // 2), data, 0) + expected = SHIFT_COUNT * CLASS_COUNT * TAP_COUNT * TAP_COUNT + if len(taps) != expected: + raise ValueError("expected %d taps, got %d" % (expected, len(taps))) + per_shift = CLASS_COUNT * TAP_COUNT * TAP_COUNT + for shift in range(SHIFT_COUNT): + chunk = taps[shift * per_shift:(shift + 1) * per_shift] + sums = { + sum(chunk[cls * 25:(cls + 1) * 25]) for cls in range(CLASS_COUNT) + } + # Every class is an interpolation filter normalised to 1.0 in Q12; the small + # spread is the original quantisation, not an extraction error. + if not all(4000 <= value <= 4200 for value in sums): + raise ValueError("shift %d filter sums out of Q12 range: %s" % (shift, sorted(sums))) + return taps + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("source", type=Path) + parser.add_argument("output", type=Path) + arguments = parser.parse_args() + + source = arguments.source.read_bytes() + digest = hashlib.sha256(source).hexdigest() + if digest != SOURCE_SHA256: + raise ValueError("expected libgcastartup.so %s, got %s" % (SOURCE_SHA256, digest)) + + taps = verify(source) + payload = struct.pack("<%dh" % len(taps), *taps) + arguments.output.parent.mkdir(parents=True, exist_ok=True) + arguments.output.write_bytes(payload) + print( + "wrote=%s bytes=%d shifts=%d classes=%d taps=%d q=%d sha256=%s" + % ( + arguments.output, + len(payload), + SHIFT_COUNT, + CLASS_COUNT, + TAP_COUNT, + Q_BITS, + hashlib.sha256(payload).hexdigest(), + ) + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/research/extract_mgc_raisr_randomness_lut.py b/scripts/research/extract_mgc_raisr_randomness_lut.py new file mode 100644 index 00000000..baa988e2 --- /dev/null +++ b/scripts/research/extract_mgc_raisr_randomness_lut.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Lift the pinned MGC V25 nano_raisr randomness LUT out of libgcastartup.so. + +The RAISR composite kernel takes this table as an input buffer. It is a static +`.data` object: the GOT slot at 0x61E70A0 carries an R_AARCH64_RELATIVE +relocation to VA 0x7C59978, and the composite entry at 0x35C8C54 is the only +consumer reached from the finish pipeline. + +Length evidence: the object is a 16x16 byte table. Bytes 0x000..0x0FF only ever +take the four dither levels {0, 5, 10, 15}, and from 0x100 onwards the bytes are +zero padding before the next `.data` object. The driver hands the kernel a +descriptor whose dynamic dimensions are all zero, so the kernel indexes the +table independently of the descriptor; the extraction below therefore only +carries the bytes and asserts the observed value set and length. + +`.data` is mapped at VA-0x4000 in the file, unlike `.rodata` where VA == offset. +""" + +from __future__ import annotations + +import argparse +import hashlib +from pathlib import Path + +SOURCE_SHA256 = "76966e7c150dfcb2795ea5b2119827a7e90b13d8c03035dbc4de583d9d12eaa6" +TABLE_VA = 0x7C59978 +TABLE_BYTES = 0x100 +DATA_FILE_BIAS = 0x4000 +LEVELS = {0, 5, 10, 15} + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("source", type=Path) + parser.add_argument("output", type=Path) + arguments = parser.parse_args() + + source = arguments.source.read_bytes() + digest = hashlib.sha256(source).hexdigest() + if digest != SOURCE_SHA256: + raise ValueError("expected libgcastartup.so %s, got %s" % (SOURCE_SHA256, digest)) + + offset = TABLE_VA - DATA_FILE_BIAS + table = source[offset:offset + TABLE_BYTES] + if len(table) != TABLE_BYTES: + raise ValueError("randomness LUT lies outside the mapped file") + unexpected = sorted(set(table) - LEVELS) + if unexpected: + raise ValueError("randomness LUT leaves the dither level set: %s" % unexpected) + tail = source[offset + TABLE_BYTES:offset + TABLE_BYTES + 0x10] + if any(tail): + raise ValueError("expected zero padding right after the 256-byte table") + + arguments.output.parent.mkdir(parents=True, exist_ok=True) + arguments.output.write_bytes(table) + print( + "wrote=%s bytes=%d levels=%s sha256=%s" + % ( + arguments.output, + len(table), + sorted(LEVELS), + hashlib.sha256(table).hexdigest(), + ) + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/research/generate_mgc_raisr_static_asm.py b/scripts/research/generate_mgc_raisr_static_asm.py new file mode 100644 index 00000000..2fbccf67 --- /dev/null +++ b/scripts/research/generate_mgc_raisr_static_asm.py @@ -0,0 +1,582 @@ +#!/usr/bin/env python3 +"""Lift the pinned MGC V25 RAISR AOT closures into static-assembly capsules. + +Three AOT kernels are extracted from the pinned libgcastartup.so: + * NanoRaisrUpscalePerShiftFRH2xInt16Opt5x5Halide (per-shift 2x luma upscale) + * HashFromOrientation2xThinOptHalide (hash / filter-class image) + * NanoRaisrCompositeHalide (RAISR + fallback composite) + +Each closure is copied verbatim from the .so; only the Halide runtime calls and +the parallel-task pointers are re-pointed at symbols provided by this project. +Image arithmetic is untouched. + +Run: uv run scripts/research/generate_mgc_raisr_static_asm.py \ + + +Boundary evidence, ABI notes and unresolved items live in +.codex-tmp/ida/mgc_v25/raisr_recon/RAISR_KERNELS.md. +""" + +from __future__ import annotations + +import argparse +import hashlib +import re +import struct +from dataclasses import dataclass +from pathlib import Path + +SOURCE_SHA256 = "76966e7c150dfcb2795ea5b2119827a7e90b13d8c03035dbc4de583d9d12eaa6" +PAGE_SIZE = 4096 +SHT_RELA = 4 +R_AARCH64_RELATIVE = 0x403 + +CAPSULE_PLACEHOLDER = "@MGC_RAISR_CAPSULE@" + +# libgcastartup.so is linked so that these sections have address == file offset. +# A capsule copies bytes by file offset, so only these sections may be lifted. +IDENTITY_MAPPED_SECTIONS = ( + (".text", 0x20549F0, 0x20549F0 + 0x4002D64), + (".rodata", 0x4A4100, 0x4A4100 + 0x17838DD), + (".data.rel.ro", 0x605C078, 0x605C078 + 0x1782A0), + (".got", 0x61D57C0, 0x61D57C0 + 0x23400), +) + +# Halide runtime entry points, resolved to the host shims declared by +# app/src/main/cpp/mgc_denoise_static/mgc_denoise_static.cpp. +HOST_TARGETS = { + 0x05F91100: "photon_mgc_halide_malloc", + 0x05F9111C: "photon_mgc_halide_free", + 0x05F93F88: "photon_mgc_halide_trace", + 0x0585F89C: "photon_mgc_halide_do_par_for", + 0x05FB8540: "memset", +} + +# C++ file that provides photon_mgc_halide_error_
shims. +ERROR_SHIM_SOURCE = Path(__file__).resolve().parents[2] / ( + "app/src/main/cpp/mgc_denoise_static/mgc_denoise_static.cpp" +) + +# Relocation slots that carry Halide parallel-task pointers, on the shared +# .got page. Every one of these must resolve inside the owning closure. +TASK_SLOTS = { + "upscale_2x": {0x61E7068: 0x3589BF0}, + "hash": {0x61E7080: 0x358F794}, + "composite": { + 0x61E7120: 0x35BD0DC, + 0x61E7128: 0x35BF998, + 0x61E7130: 0x35C2254, + 0x61E7138: 0x35C29FC, + 0x61E7140: 0x35C2FD0, + 0x61E7148: 0x35C4A44, + 0x61E7150: 0x35C64E4, + 0x61E7158: 0x35C6C30, + 0x61E7160: 0x35C86A0, + }, + # OrientationUint8ThinOptHalide worker; the wrapper ADRP at 0x35A1688 + # targets 0x61E7000 and loads [x1,#0x98]. + "orientation": {0x61E7098: 0x359B0A8}, + # RgbToGray3ChOptHalideU8 worker; the wrapper ADRP at 0x3C51394 targets + # 0x61E8000 and loads [x1,#0x630] => slot 0x61E8630. + "rgb_to_gray": {0x61E8630: 0x3C50BC8}, +} + + +@dataclass(frozen=True) +class CodeRange: + name: str + start: int + entry: int + end: int + symbol: str | None = None + + +@dataclass(frozen=True) +class CodeClosure: + name: str + ranges: tuple[CodeRange, ...] + + @property + def start(self) -> int: + return page_floor(min(value.start for value in self.ranges)) + + @property + def end(self) -> int: + return page_ceil(max(value.end for value in self.ranges)) + + @property + def entries(self) -> tuple[int, ...]: + return tuple(value.entry for value in self.ranges) + + +# --------------------------------------------------------------------------- +# Closure 1: NanoRaisrUpscalePerShiftFRH2xInt16Opt5x5Halide. +# Worker 0x3589BF0..0x358A240 was reached from the .got task pointer 0x61E7068; +# the AOT host entry 0x358A240..0x358B830 is the target of the single BL at +# 0x35899B8. Both are CFI-free and contiguous (FDE gap 0x3589BF0..0x358F370). +UPSCALE_RANGES = ( + CodeRange("RaisrUpscale2xWorker", 0x3589BF0, 0x3589BF0, 0x358A240), + CodeRange("RaisrUpscale2xEntry", 0x358A240, 0x358A240, 0x358B830, + "photon_mgc_raisr_upscale_2x"), +) + +# --------------------------------------------------------------------------- +# Closure 2: HashFromOrientation2xThinOptHalide. +# Worker 0x358F794..0x3591F3C (task pointer 0x61E7080); host entry +# 0x3591F3C..0x3592C10, target of the single BL at 0x358F5B8. +HASH_RANGES = ( + CodeRange("RaisrHashWorker", 0x358F794, 0x358F794, 0x3591F3C), + CodeRange("RaisrHashEntry", 0x3591F3C, 0x3591F3C, 0x3592C10, + "photon_mgc_raisr_hash"), +) + +# --------------------------------------------------------------------------- +# Closure 3: NanoRaisrCompositeHalide. +# The host entry at 0x35C8C54 starts nine halide_do_par_for nests whose task +# pointers are .got slots 0x61E7120..0x61E7160. Those nine task functions are +# reachable only through the .got, so the closure must be widened from the +# entry-only range 0x35C8C54..0x35CB418 to 0x35BD0DC..0x35CB418; the widened +# span is one contiguous CFI-free run and stops exactly at the CFI-covered +# function 0x35CB418. +COMPOSITE_RANGES = ( + CodeRange("RaisrCompositeTask0", 0x35BD0DC, 0x35BD0DC, 0x35BF998), + CodeRange("RaisrCompositeTask1", 0x35BF998, 0x35BF998, 0x35C2254), + CodeRange("RaisrCompositeTask2", 0x35C2254, 0x35C2254, 0x35C29FC), + CodeRange("RaisrCompositeTask3", 0x35C29FC, 0x35C29FC, 0x35C2FD0), + CodeRange("RaisrCompositeTask4", 0x35C2FD0, 0x35C2FD0, 0x35C4A44), + CodeRange("RaisrCompositeTask5", 0x35C4A44, 0x35C4A44, 0x35C64E4), + CodeRange("RaisrCompositeTask6", 0x35C64E4, 0x35C64E4, 0x35C6C30), + CodeRange("RaisrCompositeTask7", 0x35C6C30, 0x35C6C30, 0x35C86A0), + CodeRange("RaisrCompositeTask8", 0x35C86A0, 0x35C86A0, 0x35C8C54), + CodeRange("RaisrCompositeEntry", 0x35C8C54, 0x35C8C54, 0x35CB418, + "photon_mgc_raisr_composite"), +) + +# --------------------------------------------------------------------------- +# Closure 4: OrientationUint8ThinOptHalide. +# The RAISR hash kernel consumes a 3-channel orientation image, so the finish +# chain needs this kernel as well. Worker 0x359B0A8..0x359DAF4 (task pointer +# 0x61E7098), host entry 0x359DAF4..0x35A1B24; the span is one CFI-free run +# that stops exactly at the CFI-covered composite bridge 0x35A1B24. +ORIENTATION_RANGES = ( + CodeRange("RaisrOrientationWorker", 0x359B0A8, 0x359B0A8, 0x359DAF4), + CodeRange("RaisrOrientationEntry", 0x359DAF4, 0x359DAF4, 0x35A1B24, + "photon_mgc_raisr_orientation"), +) + +# --------------------------------------------------------------------------- +# Closure 5: RgbToGray3ChOptHalideU8. +# Produces the single-channel luma the RAISR chain starts from. Worker +# 0x3C50BC8..0x3C50CBC (task pointer 0x61E8630, a different .got page than the +# RAISR module), host entry 0x3C50CBC..0x3C516C0, where the next CFI-covered +# function begins. +RGB_TO_GRAY_RANGES = ( + CodeRange("RgbToGrayWorker", 0x3C50BC8, 0x3C50BC8, 0x3C50CBC), + CodeRange("RgbToGrayEntry", 0x3C50CBC, 0x3C50CBC, 0x3C516C0, + "photon_mgc_raisr_rgb_to_gray"), +) + +CODE_CLOSURES = ( + CodeClosure("upscale_2x", UPSCALE_RANGES), + CodeClosure("hash", HASH_RANGES), + CodeClosure("composite", COMPOSITE_RANGES), + CodeClosure("orientation", ORIENTATION_RANGES), + CodeClosure("rgb_to_gray", RGB_TO_GRAY_RANGES), +) +CODE_RANGES = tuple( + code_range for closure in CODE_CLOSURES for code_range in closure.ranges +) + + +def page_floor(value: int) -> int: + return value & ~(PAGE_SIZE - 1) + + +def page_ceil(value: int) -> int: + return (value + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1) + + +def sign_extend(value: int, bits: int) -> int: + sign = 1 << (bits - 1) + return (value ^ sign) - sign + + +def adrp_target(pc: int, instruction: int) -> int: + immediate = (((instruction >> 5) & 0x7FFFF) << 2) | ((instruction >> 29) & 0x3) + return page_floor(pc) + (sign_extend(immediate, 21) << 12) + + +def adr_target(pc: int, instruction: int) -> int: + immediate = (((instruction >> 5) & 0x7FFFF) << 2) | ((instruction >> 29) & 0x3) + return pc + sign_extend(immediate, 21) + + +def branch_target(pc: int, instruction: int) -> int: + return pc + (sign_extend(instruction & 0x03FFFFFF, 26) << 2) + + +def relative_imm19_target(pc: int, instruction: int) -> int: + return pc + (sign_extend((instruction >> 5) & 0x7FFFF, 19) << 2) + + +def relative_imm14_target(pc: int, instruction: int) -> int: + return pc + (sign_extend((instruction >> 5) & 0x3FFF, 14) << 2) + + +def range_for(address: int) -> CodeRange | None: + return next((value for value in CODE_RANGES if value.start <= address < value.end), None) + + +def closure_for(address: int) -> CodeClosure | None: + return next((value for value in CODE_CLOSURES if value.start <= address < value.end), None) + + +def section_for(address: int) -> str | None: + return next( + (name for name, start, end in IDENTITY_MAPPED_SECTIONS if start <= address < end), + None, + ) + + +def address_symbol(address: int) -> str: + return f"photon_mgc_raisr_address_{address:x}" + + +def page_symbol(address: int) -> str: + return f"photon_mgc_raisr_page_{address:x}" + + +def error_symbol(address: int) -> str: + return f"photon_mgc_halide_error_{address:x}" + + +def iter_elf64_rela(source: bytes): + section_offset = struct.unpack_from(" set[int]: + """Addresses of photon_mgc_halide_error_ shims defined by the C++ side.""" + text = ERROR_SHIM_SOURCE.read_text(encoding="utf-8") + addresses = {int(value, 16) for value in re.findall( + r"PHOTON_MGC_DEFINE_HALIDE_ERROR\(([0-9a-fA-F]+)\)", text)} + addresses |= {int(value, 16) for value in re.findall( + r"photon_mgc_halide_error_([0-9a-fA-F]{4,})\s*\(", text)} + if not addresses: + raise ValueError(f"no halide error shims found in {ERROR_SHIM_SOURCE}") + return addresses + + +class CapsuleWriter: + def __init__(self, source: bytes) -> None: + self.source = source + self.capsule = bytearray() + + def emit(self, lines: list[str], start: int, end: int) -> None: + if end <= start: + return + if start < 0 or end > len(self.source): + raise ValueError(f"source range 0x{start:x}..0x{end:x} is unavailable") + offset = len(self.capsule) + self.capsule.extend(self.source[start:end]) + lines.append( + f' .incbin "{CAPSULE_PLACEHOLDER}", 0x{offset:x}, 0x{end - start:x}' + ) + + +def validate_local_pc_relative(pc: int, instruction: int, closure: CodeClosure) -> None: + """Reject any PC-relative reference that leaves the lifted closure.""" + target = None + kind = "" + if instruction & 0x9F000000 == 0x10000000: + target, kind = adr_target(pc, instruction), "ADR" + elif instruction & 0x3B000000 == 0x18000000: + target, kind = relative_imm19_target(pc, instruction), "literal load" + elif instruction & 0xFF000010 == 0x54000000: + target, kind = relative_imm19_target(pc, instruction), "conditional branch" + elif instruction & 0x7E000000 == 0x34000000: + target, kind = relative_imm19_target(pc, instruction), "compare branch" + elif instruction & 0x7E000000 in (0x36000000, 0x37000000): + target, kind = relative_imm14_target(pc, instruction), "test branch" + if target is not None and not (closure.start <= target < closure.end): + raise ValueError( + f"{kind} at 0x{pc:x} escapes closure {closure.name}: 0x{target:x}" + ) + + +def validate_relocated_slot_use( + source: bytes, + closure: CodeClosure, + pages: set[int], + patched_slots: set[int], + relocations: dict[int, int], +) -> list[int]: + """Every relocated pointer slot read out of a lifted page must be patched. + + A slot that still resolves to the original .so image would make the capsule + call or dereference an address outside itself. Only pages that actually + carry relocations are inspected, so a plain `ldr xN, [xN, #imm]` into a + constant .rodata page is never mistaken for a pointer-table read. + """ + relocated_pages = {page_floor(slot) for slot in relocations} + reads: list[int] = [] + for code_range in closure.ranges: + for pc in range(code_range.start, code_range.end, 4): + instruction = struct.unpack_from("> 5) & 0x1F) != base: + continue + slot = page + ((follower >> 10) & 0xFFF) * 8 + if slot not in relocations: + break + reads.append(slot) + if slot not in patched_slots: + raise ValueError( + f"closure {closure.name} reads relocated pointer 0x{slot:x} " + f"at 0x{probe:x} -> 0x{relocations[slot]:x}, which is outside " + f"the closure" + ) + break + return reads + + +def generate(source_path: Path, output_path: Path, capsule_path: Path) -> None: + source = source_path.read_bytes() + digest = hashlib.sha256(source).hexdigest() + if digest != SOURCE_SHA256: + raise ValueError(f"expected libgcastartup.so {SOURCE_SHA256}, got {digest}") + + error_shims = defined_error_shims() + + code_pages = { + page + for closure in CODE_CLOSURES + for page in range(closure.start, closure.end, PAGE_SIZE) + } + pages = set(code_pages) + labels: dict[int, list[str]] = {} + patches: dict[int, str] = {} + external_errors: set[int] = set() + + for code_range in CODE_RANGES: + closure = closure_for(code_range.entry) + if closure is None: + raise ValueError(f"no closure owns code range {code_range.name}") + labels.setdefault(code_range.entry, []).append(address_symbol(code_range.entry)) + if code_range.symbol: + labels.setdefault(code_range.entry, []).append(code_range.symbol) + for pc in range(code_range.start, code_range.end, 4): + instruction = struct.unpack_from(" 0x{target:x} is in " + f"no closure but lives on a lifted page" + ) + if owner is not None and owner.name == closure.name: + discovered[location] = target + if discovered != expected: + raise ValueError( + f"closure {closure.name} task pointers changed: expected " + f"{ {hex(k): hex(v) for k, v in expected.items()} }, got " + f"{ {hex(k): hex(v) for k, v in discovered.items()} }" + ) + for location, target in discovered.items(): + if not (closure.start <= target < closure.end): + raise ValueError( + f"task pointer 0x{location:x} -> 0x{target:x} escapes closure " + f"{closure.name}" + ) + labels.setdefault(target, []).append(address_symbol(target)) + patched_slots[closure.name] = set(discovered) + slot_reads[closure.name] = validate_relocated_slot_use( + source, closure, pages, patched_slots[closure.name], relative_relocations + ) + if set(slot_reads[closure.name]) != set(discovered): + raise ValueError( + f"closure {closure.name} task pointer slots and their read sites " + f"disagree: slots {sorted(hex(v) for v in discovered)} vs reads " + f"{sorted(hex(v) for v in slot_reads[closure.name])}" + ) + + writer = CapsuleWriter(source) + lines = [ + "/* Generated mechanically from pinned MGC 9.7.047 V25 RAISR AOT.", + " * Do not edit; regenerate with", + " * scripts/research/generate_mgc_raisr_static_asm.py.", + " */", + "", + "#if !defined(__aarch64__)", + '#error "MGC RAISR static lift is arm64-only"', + "#endif", + "", + ] + for target in sorted(external_errors): + lines.append(f" .hidden {error_symbol(target)}") + for symbol in sorted(set(HOST_TARGETS.values()) - {"memset"}): + lines.append(f" .hidden {symbol}") + + for closure in CODE_CLOSURES: + lines.extend( + [ + "", + f'.section .text.photon_mgc.Raisr.{closure.name},"ax",@progbits', + " .p2align 12", + ] + ) + for code_range in closure.ranges: + if code_range.symbol is None: + continue + lines.extend( + [ + f" .global {code_range.symbol}", + f" .hidden {code_range.symbol}", + f" .type {code_range.symbol}, %function", + ] + ) + events = ( + set(range(closure.start, closure.end, PAGE_SIZE)) + | {address for address in labels if closure.start <= address < closure.end} + | {address for address in patches if closure.start <= address < closure.end} + ) + position = closure.start + for address in sorted(events): + writer.emit(lines, position, address) + if address % PAGE_SIZE == 0: + lines.append(f"{page_symbol(address)}:") + for symbol in dict.fromkeys(labels.get(address, [])): + lines.append(f"{symbol}:") + if address in patches: + lines.append(patches[address]) + position = address + 4 + else: + position = address + writer.emit(lines, position, closure.end) + lines.append("") + + for page in sorted(pages - code_pages): + relocations = sorted( + (location, target) + for location, target in relative_relocations.items() + if page_floor(location) == page and range_for(target) is not None + and closure_for(target) in CODE_CLOSURES + ) + section = ".data.rel.ro" if relocations else ".rodata" + flags = '"aw"' if relocations else '"a"' + lines.extend( + [ + f'.section {section}.photon_mgc.raisr_page_{page:x},{flags},@progbits', + " .p2align 12", + f"{page_symbol(page)}:", + ] + ) + position = page + for location, target in relocations: + writer.emit(lines, position, location) + lines.append(f" .xword {address_symbol(target)}") + position = location + 8 + writer.emit(lines, position, page + PAGE_SIZE) + lines.append("") + + lines.extend(['.section .note.GNU-stack,"",@progbits', ""]) + output_path.write_text("\n".join(lines), encoding="utf-8") + capsule_path.write_bytes(writer.capsule) + print( + f"generated={output_path} code_pages={len(code_pages)} data_pages=" + f"{len(pages) - len(code_pages)} patches={len(patches)} " + f"task_pointers={sum(len(v) for v in patched_slots.values())} " + f"halide_errors={len(external_errors)} capsule={capsule_path} " + f"capsule_bytes={len(writer.capsule)} " + f"capsule_sha256={hashlib.sha256(writer.capsule).hexdigest()}" + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("source", type=Path) + parser.add_argument("output", type=Path) + parser.add_argument("capsule", type=Path) + arguments = parser.parse_args() + generate(arguments.source, arguments.output, arguments.capsule) + + +if __name__ == "__main__": + main()