diff --git a/aidl/als/Android.bp b/aidl/als/Android.bp
index c9cc0e7d..3d5331e6 100644
--- a/aidl/als/Android.bp
+++ b/aidl/als/Android.bp
@@ -4,25 +4,63 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-cc_binary {
-    name: "vendor.lineage.oplus_als.service",
-    init_rc: ["vendor.lineage.oplus_als.service.rc"],
-    vintf_fragments: ["vendor.lineage.oplus_als.service.xml"],
-    relative_install_path: "hw",
+// libgui has no Rust bindings; the display queries and the capture itself are in C++.
+cc_library_static {
+    name: "libals_capture",
     system_ext_specific: true,
-    srcs: [
-        "AreaCapture.cpp",
-        "main.cpp",
-    ],
+    srcs: ["capture.cpp"],
+    export_include_dirs: ["."],
     shared_libs: [
-        "libbase",
         "libbinder",
-        "libbinder_ndk",
         "libgui",
-        "libjsoncpp",
+        "liblog",
         "libui",
         "libutils",
+    ],
+}
+
+rust_defaults {
+    name: "vendor.lineage.oplus_als.service-defaults",
+    system_ext_specific: true,
+    prefer_rlib: true,
+    srcs: ["main.rs"],
+    rustlibs: [
+        "libbinder_rs",
+        "liblog_rust",
+        "liblogger",
+        "librustutils",
+        "libserde_json",
+        "vendor.lineage.oplus_als-V1-rust",
+    ],
+    static_libs: ["libals_capture"],
+    shared_libs: [
+        "libc++",
+        "libbinder",
+        "libgui",
         "liblog",
-        "vendor.lineage.oplus_als-V1-ndk",
+        "libui",
+        "libutils",
     ],
 }
+
+rust_binary {
+    name: "vendor.lineage.oplus_als.service",
+    defaults: ["vendor.lineage.oplus_als.service-defaults"],
+    init_rc: ["vendor.lineage.oplus_als.service.rc"],
+    vintf_fragments: ["vendor.lineage.oplus_als.service.xml"],
+    relative_install_path: "hw",
+}
+
+rust_test {
+    name: "vendor.lineage.oplus_als.service-test",
+    defaults: ["vendor.lineage.oplus_als.service-defaults"],
+    test_suites: ["general-tests"],
+}
+
+cc_test {
+    name: "oplus_als_capture_listener_test",
+    system_ext_specific: true,
+    srcs: ["capture_listener_test.cpp"],
+    shared_libs: ["libbinder", "libgui", "libui", "libutils"],
+    test_suites: ["general-tests"],
+}
diff --git a/aidl/als/AreaCapture.cpp b/aidl/als/AreaCapture.cpp
deleted file mode 100644
index b90daf24..00000000
--- a/aidl/als/AreaCapture.cpp
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
- * Copyright (C) 2021-2024 The LineageOS Project
- *
- * SPDX-License-Identifier: Apache-2.0
- */
-
-#include "AreaCapture.h"
-
-#include <android-base/properties.h>
-#include <android/gui/SecureLayerMode.h>
-#include <json/reader.h>
-#include <gui/AidlUtil.h>
-#include <gui/SurfaceComposerClient.h>
-#include <gui/SyncScreenCaptureListener.h>
-#include <ui/ColorSpace.h>
-#include <ui/DisplayState.h>
-#include <ui/DynamicDisplayInfo.h>
-#include <ui/PixelFormat.h>
-#include <ui/StaticDisplayInfo.h>
-
-#include <algorithm>
-#include <array>
-#include <cmath>
-#include <fstream>
-#include <sstream>
-
-using android::ColorSpace;
-using android::DisplayCaptureArgs;
-using android::GraphicBuffer;
-using android::IBinder;
-using android::NO_ERROR;
-using android::PhysicalDisplayId;
-using android::Rect;
-using android::ScreenshotClient;
-using android::sp;
-using android::SurfaceComposerClient;
-using android::SyncScreenCaptureListener;
-using android::base::GetProperty;
-using android::gui::ScreenCaptureResults;
-using android::gui::SecureLayerMode;
-using android::gui::aidl_utils::toARect;
-using android::ui::PixelFormat;
-
-namespace ui = ::android::ui;
-
-namespace aidl {
-namespace vendor {
-namespace lineage {
-namespace oplus_als {
-
-namespace {
-
-constexpr char kWeightsPath[] = "/odm/etc/display/cwb_weightspos.json";
-
-const std::array<float, 256>& GetSrgbToLinearLut() {
-    static const std::array<float, 256> lut = [] {
-        std::array<float, 256> values;
-        const auto decode = ColorSpace::sRGB().getEOTF();
-        for (size_t value = 0; value < values.size(); ++value) {
-            values[value] = decode(value / 255.0f);
-        }
-        return values;
-    }();
-    return lut;
-}
-
-float LinearToSrgb(float value) {
-    return ColorSpace::sRGB().getOETF()(std::clamp(value, 0.0f, 1.0f)) * 255.0f;
-}
-
-// Stock CWB weights for the grab area, used only when they cover exactly that many pixels.
-std::vector<float> LoadWeights(const Rect& rect) {
-    std::ifstream stream(kWeightsPath);
-    if (!stream.is_open()) {
-        return {};
-    }
-
-    Json::CharReaderBuilder builder;
-    Json::Value root;
-    std::string error;
-    const auto count = static_cast<Json::ArrayIndex>(rect.getWidth() * rect.getHeight());
-    if (!Json::parseFromStream(builder, stream, &root, &error) || !root["Weights"].isArray() ||
-        root["Weights"].size() != count) {
-        ALOGW("%s does not match the grab area; using unweighted sampling", kWeightsPath);
-        return {};
-    }
-
-    std::vector<float> weights;
-    weights.reserve(count);
-    for (const auto& value : root["Weights"]) {
-        if (!value.isNumeric() || value.asDouble() < 0) {
-            ALOGW("Invalid weight in %s; using unweighted sampling", kWeightsPath);
-            return {};
-        }
-        weights.push_back(value.asFloat());
-    }
-    ALOGI("Loaded %zu grab area weights", weights.size());
-    return weights;
-}
-
-}  // namespace
-
-AreaCapture::AreaCapture() {
-    int left = 0, top = 0, right = 0, bottom = 0;
-    std::istringstream is(GetProperty("vendor.sensors.als_correction.grabrect", ""));
-
-    is >> left >> top >> right >> bottom;
-    if (is.fail() || left < 0 || top < 0 || right <= left || bottom <= top) {
-        ALOGE("No valid screenshot grab area config");
-        return;
-    }
-
-    ALOGI("Screenshot grab area: %d %d %d %d", left, top, right, bottom);
-    m_screenshot_rect = Rect(left, top, right, bottom);
-    m_weights = LoadWeights(m_screenshot_rect);
-}
-
-// The grab area is in panel pixels of the largest display mode. captureDisplay crops in layer
-// stack space, which follows the display rotation and any resolution or size override.
-std::optional<AreaCapture::CaptureArea> AreaCapture::getCaptureArea(
-        PhysicalDisplayId displayId, const sp<IBinder>& displayToken) const {
-    ui::StaticDisplayInfo staticInfo;
-    ui::DynamicDisplayInfo dynamicInfo;
-    ui::DisplayState state;
-    if (SurfaceComposerClient::getStaticDisplayInfo(displayId.value, &staticInfo) != NO_ERROR ||
-        SurfaceComposerClient::getDynamicDisplayInfoFromId(displayId.value, &dynamicInfo) !=
-                NO_ERROR ||
-        SurfaceComposerClient::getDisplayState(displayToken, &state) != NO_ERROR) {
-        return std::nullopt;
-    }
-
-    ui::Size panel;
-    for (const auto& mode : dynamicInfo.supportedDisplayModes) {
-        if (mode.resolution.width * mode.resolution.height > panel.width * panel.height) {
-            panel = mode.resolution;
-        }
-    }
-    const auto& layerStack = state.layerStackSpaceRect;
-    if (panel.width <= 0 || panel.height <= 0 || layerStack.width <= 0 ||
-        layerStack.height <= 0) {
-        return std::nullopt;
-    }
-
-    const float l = static_cast<float>(m_screenshot_rect.left) / panel.width;
-    const float t = static_cast<float>(m_screenshot_rect.top) / panel.height;
-    const float r = static_cast<float>(m_screenshot_rect.right) / panel.width;
-    const float b = static_cast<float>(m_screenshot_rect.bottom) / panel.height;
-    const auto rotation = state.orientation + staticInfo.installOrientation;
-    float left, top, right, bottom;
-    switch (rotation) {
-        case ui::ROTATION_90:
-            left = t, top = 1.0f - r, right = b, bottom = 1.0f - l;
-            break;
-        case ui::ROTATION_180:
-            left = 1.0f - r, top = 1.0f - b, right = 1.0f - l, bottom = 1.0f - t;
-            break;
-        case ui::ROTATION_270:
-            left = 1.0f - b, top = l, right = 1.0f - t, bottom = r;
-            break;
-        default:
-            left = l, top = t, right = r, bottom = b;
-            break;
-    }
-
-    const Rect crop(std::max(0, static_cast<int32_t>(std::floor(left * layerStack.width))),
-                    std::max(0, static_cast<int32_t>(std::floor(top * layerStack.height))),
-                    std::min(layerStack.width,
-                             static_cast<int32_t>(std::ceil(right * layerStack.width))),
-                    std::min(layerStack.height,
-                             static_cast<int32_t>(std::ceil(bottom * layerStack.height))));
-    if (crop.isEmpty()) {
-        return std::nullopt;
-    }
-    return CaptureArea{crop, rotation};
-}
-
-ndk::ScopedAStatus AreaCapture::getAreaBrightness(AreaRgbCaptureResult* _aidl_return) {
-    if (m_screenshot_rect.isEmpty()) {
-        return ndk::ScopedAStatus::fromServiceSpecificError(-1);
-    }
-
-    // See frameworks/base/services/core/jni/com_android_server_display_DisplayControl.cpp and
-    // frameworks/base/core/java/android/view/SurfaceControl.java
-    const auto displayIds = SurfaceComposerClient::getPhysicalDisplayIds();
-    if (displayIds.empty()) {
-        ALOGE("No physical display");
-        return ndk::ScopedAStatus::fromServiceSpecificError(-1);
-    }
-    const auto displayToken = SurfaceComposerClient::getPhysicalDisplayToken(displayIds[0]);
-    if (displayToken == nullptr) {
-        ALOGE("No display token");
-        return ndk::ScopedAStatus::fromServiceSpecificError(-1);
-    }
-    const auto area = getCaptureArea(displayIds[0], displayToken);
-    if (!area.has_value()) {
-        ALOGE("Unable to map the grab area to the display");
-        return ndk::ScopedAStatus::fromServiceSpecificError(-1);
-    }
-
-    // Weighted captures are scaled back to one pixel per panel pixel, in layer stack orientation.
-    const int32_t panelWidth = m_screenshot_rect.getWidth();
-    const int32_t panelHeight = m_screenshot_rect.getHeight();
-    const bool transposed = area->rotation == ui::ROTATION_90 ||
-                            area->rotation == ui::ROTATION_270;
-    const int32_t captureWidth =
-            m_weights.empty() ? area->crop.getWidth() : (transposed ? panelHeight : panelWidth);
-    const int32_t captureHeight =
-            m_weights.empty() ? area->crop.getHeight() : (transposed ? panelWidth : panelHeight);
-
-    DisplayCaptureArgs displayCaptureArgs;
-    displayCaptureArgs.displayToken = displayToken;
-    displayCaptureArgs.captureArgs.pixelFormat = ::android::PIXEL_FORMAT_RGBA_8888;
-    displayCaptureArgs.captureArgs.sourceCrop = toARect(area->crop);
-    displayCaptureArgs.width = captureWidth;
-    displayCaptureArgs.height = captureHeight;
-    displayCaptureArgs.captureArgs.secureLayerMode = SecureLayerMode::Capture;
-
-    sp<SyncScreenCaptureListener> captureListener = new SyncScreenCaptureListener();
-    if (ScreenshotClient::captureDisplay(displayCaptureArgs, captureListener) != NO_ERROR) {
-        ALOGE("Capture failed");
-        return ndk::ScopedAStatus::fromServiceSpecificError(-1);
-    }
-
-    auto captureResults = captureListener->waitForResults();
-    if (!captureResults.fenceResult.ok() || captureResults.buffer == nullptr) {
-        ALOGE("Fence result error");
-        return ndk::ScopedAStatus::fromServiceSpecificError(-1);
-    }
-
-    uint8_t* out = nullptr;
-    if (captureResults.buffer->lock(GraphicBuffer::USAGE_SW_READ_OFTEN,
-                                    reinterpret_cast<void**>(&out)) != NO_ERROR ||
-        out == nullptr) {
-        ALOGE("Unable to map the capture buffer");
-        return ndk::ScopedAStatus::fromServiceSpecificError(-1);
-    }
-
-    const auto resultWidth = captureResults.buffer->getWidth();
-    const auto resultHeight = captureResults.buffer->getHeight();
-    const auto stride = captureResults.buffer->getStride();
-
-    const bool weighted = !m_weights.empty() && resultWidth == static_cast<uint32_t>(captureWidth) &&
-                          resultHeight == static_cast<uint32_t>(captureHeight);
-
-    // The capture is sRGB encoded; average in linear light like the CWB path does.
-    const auto& lut = GetSrgbToLinearLut();
-    float rsum = 0.0f, gsum = 0.0f, bsum = 0.0f, weightSum = 0.0f;
-    for (uint32_t y = 0; y < resultHeight; y++) {
-        for (uint32_t x = 0; x < resultWidth; x++) {
-            float weight = 1.0f;
-            if (weighted) {
-                int32_t panelX, panelY;
-                switch (area->rotation) {
-                    case ui::ROTATION_90:
-                        panelX = panelWidth - 1 - y, panelY = x;
-                        break;
-                    case ui::ROTATION_180:
-                        panelX = panelWidth - 1 - x, panelY = panelHeight - 1 - y;
-                        break;
-                    case ui::ROTATION_270:
-                        panelX = y, panelY = panelHeight - 1 - x;
-                        break;
-                    default:
-                        panelX = x, panelY = y;
-                        break;
-                }
-                weight = m_weights[panelY * panelWidth + panelX];
-            }
-            const uint8_t* pixel = out + (y * stride + x) * 4;
-            rsum += lut[pixel[0]] * weight;
-            gsum += lut[pixel[1]] * weight;
-            bsum += lut[pixel[2]] * weight;
-            weightSum += weight;
-        }
-    }
-    captureResults.buffer->unlock();
-
-    if (weightSum <= 0.0f) {
-        return ndk::ScopedAStatus::fromServiceSpecificError(-1);
-    }
-    _aidl_return->r = LinearToSrgb(rsum / weightSum);
-    _aidl_return->g = LinearToSrgb(gsum / weightSum);
-    _aidl_return->b = LinearToSrgb(bsum / weightSum);
-
-    return ndk::ScopedAStatus::ok();
-}
-
-}  // namespace oplus_als
-}  // namespace lineage
-}  // namespace vendor
-}  // namespace aidl
diff --git a/aidl/als/AreaCapture.h b/aidl/als/AreaCapture.h
deleted file mode 100644
index 802af5c8..00000000
--- a/aidl/als/AreaCapture.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2021-2024 The LineageOS Project
- *
- * SPDX-License-Identifier: Apache-2.0
- */
-
-#pragma once
-
-#include <aidl/vendor/lineage/oplus_als/BnAreaCapture.h>
-#include <ui/DisplayId.h>
-#include <ui/Rect.h>
-#include <ui/Rotation.h>
-
-#include <optional>
-#include <vector>
-
-namespace aidl {
-namespace vendor {
-namespace lineage {
-namespace oplus_als {
-
-class AreaCapture : public BnAreaCapture {
-  public:
-    AreaCapture();
-    ndk::ScopedAStatus getAreaBrightness(AreaRgbCaptureResult* _aidl_return) override;
-
-  private:
-    struct CaptureArea {
-        ::android::Rect crop;
-        ::android::ui::Rotation rotation;
-    };
-
-    std::optional<CaptureArea> getCaptureArea(
-            ::android::PhysicalDisplayId displayId,
-            const ::android::sp<::android::IBinder>& displayToken) const;
-
-    ::android::Rect m_screenshot_rect;
-    // Per-pixel weights of the grab area in panel orientation, row major.
-    std::vector<float> m_weights;
-};
-
-}  // namespace oplus_als
-}  // namespace lineage
-}  // namespace vendor
-}  // namespace aidl
diff --git a/aidl/als/main.cpp b/aidl/als/main.cpp
deleted file mode 100644
index 0e5537e8..00000000
--- a/aidl/als/main.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2024 The LineageOS Project
- *
- * SPDX-License-Identifier: Apache-2.0
- */
-
-#include "AreaCapture.h"
-
-#include <android-base/logging.h>
-#include <android/binder_manager.h>
-#include <android/binder_process.h>
-
-using ::aidl::vendor::lineage::oplus_als::AreaCapture;
-
-int main() {
-    ABinderProcess_setThreadPoolMaxThreadCount(0);
-    ABinderProcess_startThreadPool();
-    std::shared_ptr<AreaCapture> ac = ndk::SharedRefBase::make<AreaCapture>();
-
-    const auto instance = std::string(AreaCapture::descriptor) + "/default";
-    binder_status_t status = AServiceManager_addService(ac->asBinder().get(), instance.c_str());
-    CHECK_EQ(status, STATUS_OK);
-
-    ABinderProcess_joinThreadPool();
-    return EXIT_FAILURE;  // should not reach
-}
diff --git a/aidl/als/area.rs b/aidl/als/area.rs
new file mode 100644
index 00000000..db430b02
--- /dev/null
+++ b/aidl/als/area.rs
@@ -0,0 +1,429 @@
+/*
+ * Copyright (C) 2021-2024 The LineageOS Project
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+//! Display-independent parts of the area capture: grab area, weights, crop mapping and
+//! averaging.
+
+use std::sync::OnceLock;
+
+/// A rectangle in pixels; right and bottom are exclusive.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Rect {
+    pub left: i32,
+    pub top: i32,
+    pub right: i32,
+    pub bottom: i32,
+}
+
+impl Rect {
+    pub fn width(&self) -> i32 {
+        self.right - self.left
+    }
+
+    pub fn height(&self) -> i32 {
+        self.bottom - self.top
+    }
+
+    pub fn is_empty(&self) -> bool {
+        self.width() <= 0 || self.height() <= 0
+    }
+}
+
+/// Primary display state needed to place the grab area.
+#[derive(Clone, Copy, Debug)]
+pub struct Geometry {
+    /// Resolution of the largest display mode.
+    pub panel_width: i32,
+    pub panel_height: i32,
+    pub layer_stack_width: i32,
+    pub layer_stack_height: i32,
+    /// ui::Rotation of the layer stack relative to the panel, 0-3.
+    pub rotation: i32,
+}
+
+/// Grab area weights in panel orientation, row major.
+pub struct Weighting<'a> {
+    pub weights: &'a [f32],
+    pub rotation: i32,
+    pub panel_width: i32,
+    pub panel_height: i32,
+}
+
+/// Parses vendor.sensors.als_correction.grabrect ("left top right bottom").
+pub fn parse_grab_rect(value: &str) -> Option<Rect> {
+    let mut values = value.split_whitespace().map(str::parse::<i32>);
+    let mut next = || values.next()?.ok();
+    let rect = Rect {
+        left: next()?,
+        top: next()?,
+        right: next()?,
+        bottom: next()?,
+    };
+    if rect.left < 0 || rect.top < 0 || rect.right <= rect.left || rect.bottom <= rect.top {
+        return None;
+    }
+    Some(rect)
+}
+
+/// Parses the stock CWB weights, which must cover exactly `count` pixels.
+pub fn parse_weights(json: &str, count: usize) -> Result<Vec<f32>, &'static str> {
+    let root: serde_json::Value =
+        serde_json::from_str(json).map_err(|_| "does not match the grab area")?;
+    let values = root
+        .get("Weights")
+        .and_then(|weights| weights.as_array())
+        .filter(|weights| weights.len() == count)
+        .ok_or("does not match the grab area")?;
+    values
+        .iter()
+        .map(|value| {
+            value
+                .as_f64()
+                .map(|w| w as f32)
+                .filter(|w| w.is_finite() && *w >= 0.0)
+        })
+        .collect::<Option<Vec<f32>>>()
+        .ok_or("has an invalid weight")
+}
+
+/// Maps the grab area, given in panel pixels of the largest display mode, to a crop in layer
+/// stack space, which follows the display rotation and any resolution or size override.
+pub fn capture_crop(rect: &Rect, geometry: &Geometry) -> Option<Rect> {
+    let (panel_w, panel_h) = (geometry.panel_width, geometry.panel_height);
+    let (stack_w, stack_h) = (geometry.layer_stack_width, geometry.layer_stack_height);
+    if panel_w <= 0
+        || panel_h <= 0
+        || stack_w <= 0
+        || stack_h <= 0
+        || rect.left < 0
+        || rect.top < 0
+        || rect.right <= rect.left
+        || rect.bottom <= rect.top
+        || rect.right > panel_w
+        || rect.bottom > panel_h
+        || !(0..=3).contains(&geometry.rotation)
+    {
+        return None;
+    }
+
+    let l = rect.left as f32 / panel_w as f32;
+    let t = rect.top as f32 / panel_h as f32;
+    let r = rect.right as f32 / panel_w as f32;
+    let b = rect.bottom as f32 / panel_h as f32;
+    let (left, top, right, bottom) = match geometry.rotation {
+        1 => (t, 1.0 - r, b, 1.0 - l),
+        2 => (1.0 - r, 1.0 - b, 1.0 - l, 1.0 - t),
+        3 => (1.0 - b, l, 1.0 - t, r),
+        _ => (l, t, r, b),
+    };
+
+    let crop = Rect {
+        left: ((left * stack_w as f32).floor() as i32).max(0),
+        top: ((top * stack_h as f32).floor() as i32).max(0),
+        right: ((right * stack_w as f32).ceil() as i32).min(stack_w),
+        bottom: ((bottom * stack_h as f32).ceil() as i32).min(stack_h),
+    };
+    (!crop.is_empty()).then_some(crop)
+}
+
+/// Index into the panel-oriented weights for capture pixel (x, y).
+pub fn panel_index(rotation: i32, x: u32, y: u32, panel_w: i32, panel_h: i32) -> Option<usize> {
+    let (x, y, w, h) = (
+        i64::from(x),
+        i64::from(y),
+        i64::from(panel_w),
+        i64::from(panel_h),
+    );
+    let (px, py) = match rotation {
+        1 => (w - 1 - y, x),
+        2 => (w - 1 - x, h - 1 - y),
+        3 => (y, h - 1 - x),
+        _ => (x, y),
+    };
+    if px < 0 || py < 0 || px >= w || py >= h {
+        return None;
+    }
+    usize::try_from(py * w + px).ok()
+}
+
+// sRGB transfer parameters as in frameworks/native/libs/ui/ColorSpace.cpp.
+const SRGB_A: f32 = 1.0 / 1.055;
+const SRGB_B: f32 = 0.055 / 1.055;
+const SRGB_C: f32 = 1.0 / 12.92;
+const SRGB_D: f32 = 0.04045;
+const SRGB_G: f32 = 2.4;
+
+fn srgb_eotf(x: f32) -> f32 {
+    if x >= SRGB_D {
+        (SRGB_A * x + SRGB_B).powf(SRGB_G)
+    } else {
+        SRGB_C * x
+    }
+}
+
+fn srgb_oetf(x: f32) -> f32 {
+    if x >= SRGB_D * SRGB_C {
+        (x.powf(1.0 / SRGB_G) - SRGB_B) / SRGB_A
+    } else {
+        x / SRGB_C
+    }
+}
+
+fn srgb_to_linear_lut() -> &'static [f32; 256] {
+    static LUT: OnceLock<[f32; 256]> = OnceLock::new();
+    LUT.get_or_init(|| std::array::from_fn(|value| srgb_eotf(value as f32 / 255.0)))
+}
+
+fn linear_to_srgb(value: f32) -> f32 {
+    srgb_oetf(value.clamp(0.0, 1.0)) * 255.0
+}
+
+/// Averages an RGBA_8888 capture in linear light, like the CWB path does, and returns sRGB
+/// encoded values in 0-255. `stride` is in pixels.
+pub fn average_rgb(
+    pixels: &[u8],
+    width: u32,
+    height: u32,
+    stride: u32,
+    weighting: Option<&Weighting>,
+) -> Option<[f32; 3]> {
+    if width == 0 || height == 0 || stride < width {
+        return None;
+    }
+    let needed = (height as usize - 1)
+        .checked_mul(stride as usize)?
+        .checked_add(width as usize)?
+        .checked_mul(4)?;
+    if pixels.len() < needed {
+        return None;
+    }
+    let lut = srgb_to_linear_lut();
+    // Finite f32 weights can still overflow a f32 sum; accumulate in f64.
+    let (mut r, mut g, mut b, mut weight_sum) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
+    for y in 0..height {
+        for x in 0..width {
+            let weight = match weighting {
+                Some(w) => *w.weights.get(panel_index(
+                    w.rotation,
+                    x,
+                    y,
+                    w.panel_width,
+                    w.panel_height,
+                )?)?,
+                None => 1.0,
+            };
+            if !weight.is_finite() || weight < 0.0 {
+                return None;
+            }
+            let weight = f64::from(weight);
+            let offset = (y as usize * stride as usize + x as usize) * 4;
+            let pixel = pixels.get(offset..offset + 3)?;
+            r += f64::from(lut[usize::from(pixel[0])]) * weight;
+            g += f64::from(lut[usize::from(pixel[1])]) * weight;
+            b += f64::from(lut[usize::from(pixel[2])]) * weight;
+            weight_sum += weight;
+        }
+    }
+    if weight_sum <= 0.0 {
+        return None;
+    }
+    Some([
+        linear_to_srgb((r / weight_sum) as f32),
+        linear_to_srgb((g / weight_sum) as f32),
+        linear_to_srgb((b / weight_sum) as f32),
+    ])
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn rect(left: i32, top: i32, right: i32, bottom: i32) -> Rect {
+        Rect {
+            left,
+            top,
+            right,
+            bottom,
+        }
+    }
+
+    #[test]
+    fn grab_rect() {
+        assert_eq!(
+            parse_grab_rect("1010 148 1048 190"),
+            Some(rect(1010, 148, 1048, 190))
+        );
+        assert_eq!(parse_grab_rect("  1 2   3 4 extra"), Some(rect(1, 2, 3, 4)));
+        assert_eq!(parse_grab_rect(""), None);
+        assert_eq!(parse_grab_rect("1 2 3"), None);
+        assert_eq!(parse_grab_rect("-1 2 3 4"), None);
+        assert_eq!(parse_grab_rect("3 2 3 4"), None);
+        assert_eq!(parse_grab_rect("1 4 3 4"), None);
+        assert_eq!(parse_grab_rect("a b c d"), None);
+    }
+
+    #[test]
+    fn weights() {
+        assert_eq!(
+            parse_weights(r#"{"Weights": [0.5, 1, 0]}"#, 3),
+            Ok(vec![0.5, 1.0, 0.0])
+        );
+        assert!(parse_weights(r#"{"Weights": [1, 1]}"#, 3).is_err());
+        assert!(parse_weights(r#"{"Weights": [1, -1, 1]}"#, 3).is_err());
+        assert!(parse_weights(r#"{"Weights": [1, "x", 1]}"#, 3).is_err());
+        assert!(parse_weights(r#"{"Other": [1, 1, 1]}"#, 3).is_err());
+        assert!(parse_weights("not json", 3).is_err());
+    }
+
+    #[test]
+    fn malformed_geometry_does_not_overflow() {
+        assert_eq!(parse_grab_rect("2147483647 0 -2147483648 1"), None);
+        assert_eq!(parse_grab_rect("0 2147483647 1 -2147483648"), None);
+        let g = Geometry {
+            panel_width: 100,
+            panel_height: 200,
+            layer_stack_width: 100,
+            layer_stack_height: 200,
+            rotation: 0,
+        };
+        assert_eq!(capture_crop(&rect(90, 0, 110, 20), &g), None);
+        assert_eq!(capture_crop(&rect(1, 0, i32::MIN, 20), &g), None);
+        assert!(parse_weights(r#"{"Weights": [1e100]}"#, 1).is_err());
+    }
+
+    #[test]
+    fn invalid_buffers_and_extreme_weights() {
+        let pixels = [255u8; 8];
+        assert_eq!(average_rgb(&pixels, 2, 1, 1, None), None);
+        assert_eq!(average_rgb(&pixels[..7], 2, 1, 2, None), None);
+        assert_eq!(average_rgb(&pixels, 0, 1, 2, None), None);
+        for weights in [[f32::NAN, 1.0], [f32::INFINITY, 1.0], [-1.0, 1.0]] {
+            let w = Weighting {
+                weights: &weights,
+                rotation: 0,
+                panel_width: 2,
+                panel_height: 1,
+            };
+            assert_eq!(average_rgb(&pixels, 2, 1, 2, Some(&w)), None);
+        }
+        let w = Weighting {
+            weights: &[f32::MAX, f32::MAX],
+            rotation: 0,
+            panel_width: 2,
+            panel_height: 1,
+        };
+        for value in average_rgb(&pixels, 2, 1, 2, Some(&w)).unwrap() {
+            assert!(value.is_finite() && (value - 255.0).abs() < 1e-3);
+        }
+    }
+
+    #[test]
+    fn crop_in_every_rotation() {
+        // Exact binary fractions so float rounding cannot move the edges.
+        let area = rect(16, 32, 48, 96);
+        let geometry = |rotation, stack_w, stack_h| Geometry {
+            panel_width: 128,
+            panel_height: 256,
+            layer_stack_width: stack_w,
+            layer_stack_height: stack_h,
+            rotation,
+        };
+        assert_eq!(
+            capture_crop(&area, &geometry(0, 128, 256)),
+            Some(rect(16, 32, 48, 96))
+        );
+        assert_eq!(
+            capture_crop(&area, &geometry(1, 256, 128)),
+            Some(rect(32, 80, 96, 112))
+        );
+        assert_eq!(
+            capture_crop(&area, &geometry(2, 128, 256)),
+            Some(rect(80, 160, 112, 224))
+        );
+        assert_eq!(
+            capture_crop(&area, &geometry(3, 256, 128)),
+            Some(rect(160, 16, 224, 48))
+        );
+        // Half resolution override.
+        assert_eq!(
+            capture_crop(&area, &geometry(0, 64, 128)),
+            Some(rect(8, 16, 24, 48))
+        );
+        assert_eq!(capture_crop(&area, &geometry(0, 0, 256)), None);
+    }
+
+    #[test]
+    fn panel_indices() {
+        // Panel is 2 wide and 3 tall; rotated captures are 3 wide and 2 tall.
+        assert_eq!(panel_index(0, 1, 2, 2, 3), Some(5));
+        assert_eq!(panel_index(1, 0, 0, 2, 3), Some(1));
+        assert_eq!(panel_index(2, 0, 0, 2, 3), Some(5));
+        assert_eq!(panel_index(3, 0, 0, 2, 3), Some(4));
+        assert_eq!(panel_index(0, 2, 0, 2, 3), None);
+        assert_eq!(panel_index(1, 0, 2, 2, 3), None);
+    }
+
+    #[test]
+    fn weights_follow_all_four_rotations() {
+        // Panel 2x3: only its top-right pixel has nonzero weight. The corresponding
+        // capture positions are explicit, independent of panel_index().
+        for (rotation, width, height, red_index) in
+            [(0, 2, 3, 1), (1, 3, 2, 0), (2, 2, 3, 4), (3, 3, 2, 5)]
+        {
+            let mut pixels = [0u8; 24];
+            pixels[red_index * 4] = 255;
+            let weighting = Weighting {
+                weights: &[0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
+                rotation,
+                panel_width: 2,
+                panel_height: 3,
+            };
+            let rgb = average_rgb(&pixels, width, height, width, Some(&weighting)).unwrap();
+            assert!((rgb[0] - 255.0).abs() < 1e-3);
+            assert_eq!((rgb[1], rgb[2]), (0.0, 0.0));
+        }
+    }
+
+    #[test]
+    fn srgb_curves() {
+        assert_eq!(srgb_eotf(0.0), 0.0);
+        assert!((srgb_eotf(1.0) - 1.0).abs() < 1e-6);
+        assert!((srgb_eotf(0.5) - 0.214_041).abs() < 1e-5);
+        for value in [0.0f32, 0.01, 0.2, 0.5, 0.9, 1.0] {
+            assert!((srgb_oetf(srgb_eotf(value)) - value).abs() < 1e-5);
+        }
+    }
+
+    #[test]
+    fn averaging() {
+        // 2x1 capture with a stride of 4 pixels: one red, one black pixel.
+        let mut pixels = vec![0u8; 4 * 4];
+        pixels[..4].copy_from_slice(&[255, 0, 0, 255]);
+        pixels[7] = 255;
+
+        let [r, g, b] = average_rgb(&pixels, 2, 1, 4, None).unwrap();
+        assert!((r - srgb_oetf(0.5) * 255.0).abs() < 1e-3);
+        assert_eq!((g, b), (0.0, 0.0));
+
+        let only_red = Weighting {
+            weights: &[1.0, 0.0],
+            rotation: 0,
+            panel_width: 2,
+            panel_height: 1,
+        };
+        let [r, _, _] = average_rgb(&pixels, 2, 1, 4, Some(&only_red)).unwrap();
+        assert!((r - 255.0).abs() < 1e-3);
+
+        let none = Weighting {
+            weights: &[0.0, 0.0],
+            rotation: 0,
+            panel_width: 2,
+            panel_height: 1,
+        };
+        assert_eq!(average_rgb(&pixels, 2, 1, 4, Some(&none)), None);
+        assert_eq!(average_rgb(&pixels[..6], 2, 1, 4, None), None);
+    }
+}
diff --git a/aidl/als/capture.cpp b/aidl/als/capture.cpp
new file mode 100644
index 00000000..6f22e482
--- /dev/null
+++ b/aidl/als/capture.cpp
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2021-2024 The LineageOS Project
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+// libgui has no Rust bindings, so the display queries and the screen capture live here behind a
+// C ABI. Everything else (grab area, weights, crop mapping, averaging) is in Rust.
+
+#include "capture.h"
+#include "capture_listener.h"
+
+#include <android/gui/SecureLayerMode.h>
+#include <gui/AidlUtil.h>
+#include <gui/SurfaceComposerClient.h>
+#include <log/log.h>
+#include <ui/DisplayState.h>
+#include <ui/DynamicDisplayInfo.h>
+#include <ui/PixelFormat.h>
+#include <ui/StaticDisplayInfo.h>
+
+using android::DisplayCaptureArgs;
+using android::GraphicBuffer;
+using android::IBinder;
+using android::NO_ERROR;
+using android::PhysicalDisplayId;
+using android::Rect;
+using android::ScreenshotClient;
+using android::sp;
+using android::SurfaceComposerClient;
+using android::gui::SecureLayerMode;
+using android::gui::aidl_utils::toARect;
+
+namespace ui = ::android::ui;
+
+namespace {
+
+// See frameworks/base/services/core/jni/com_android_server_display_DisplayControl.cpp and
+// frameworks/base/core/java/android/view/SurfaceControl.java
+bool GetPrimaryDisplay(PhysicalDisplayId* id, sp<IBinder>* token) {
+    const auto displayIds = SurfaceComposerClient::getPhysicalDisplayIds();
+    if (displayIds.empty()) {
+        ALOGE("No physical display");
+        return false;
+    }
+    *id = displayIds[0];
+    *token = SurfaceComposerClient::getPhysicalDisplayToken(*id);
+    if (*token == nullptr) {
+        ALOGE("No display token");
+        return false;
+    }
+    return true;
+}
+
+}  // namespace
+
+extern "C" bool als_get_display_geometry(AlsDisplayGeometry* out) {
+    PhysicalDisplayId displayId;
+    sp<IBinder> displayToken;
+    if (!GetPrimaryDisplay(&displayId, &displayToken)) {
+        return false;
+    }
+
+    ui::StaticDisplayInfo staticInfo;
+    ui::DynamicDisplayInfo dynamicInfo;
+    ui::DisplayState state;
+    if (SurfaceComposerClient::getStaticDisplayInfo(displayId.value, &staticInfo) != NO_ERROR ||
+        SurfaceComposerClient::getDynamicDisplayInfoFromId(displayId.value, &dynamicInfo) !=
+                NO_ERROR ||
+        SurfaceComposerClient::getDisplayState(displayToken, &state) != NO_ERROR) {
+        return false;
+    }
+
+    ui::Size panel;
+    for (const auto& mode : dynamicInfo.supportedDisplayModes) {
+        if (mode.resolution.width * mode.resolution.height > panel.width * panel.height) {
+            panel = mode.resolution;
+        }
+    }
+
+    out->panel_width = panel.width;
+    out->panel_height = panel.height;
+    out->layer_stack_width = state.layerStackSpaceRect.width;
+    out->layer_stack_height = state.layerStackSpaceRect.height;
+    // ui::Rotation addition wraps around.
+    out->rotation = static_cast<int32_t>(state.orientation + staticInfo.installOrientation);
+    return true;
+}
+
+extern "C" bool als_capture(const AlsRect* crop, int32_t width, int32_t height,
+                            AlsPixelsCallback callback, void* context) {
+    PhysicalDisplayId displayId;
+    sp<IBinder> displayToken;
+    if (!GetPrimaryDisplay(&displayId, &displayToken)) {
+        return false;
+    }
+
+    DisplayCaptureArgs displayCaptureArgs;
+    displayCaptureArgs.displayToken = displayToken;
+    displayCaptureArgs.captureArgs.pixelFormat = ::android::PIXEL_FORMAT_RGBA_8888;
+    displayCaptureArgs.captureArgs.sourceCrop =
+            toARect(Rect(crop->left, crop->top, crop->right, crop->bottom));
+    displayCaptureArgs.width = width;
+    displayCaptureArgs.height = height;
+    displayCaptureArgs.captureArgs.secureLayerMode = SecureLayerMode::Capture;
+
+    sp<AlsCaptureListener> captureListener = new AlsCaptureListener();
+    if (ScreenshotClient::captureDisplay(displayCaptureArgs, captureListener) != NO_ERROR) {
+        ALOGE("Capture failed");
+        return false;
+    }
+
+    android::gui::ScreenCaptureResults captureResults;
+    if (!captureListener->waitForResults(&captureResults)) {
+        ALOGE("Timed out waiting for capture callback");
+        return false;
+    }
+    if (!captureResults.fenceResult.ok() || captureResults.buffer == nullptr) {
+        ALOGE("Fence result error");
+        return false;
+    }
+
+    if (captureResults.fenceResult.value()->wait(2000) != NO_ERROR) {
+        ALOGE("Timed out waiting for capture fence");
+        return false;
+    }
+
+    uint8_t* pixels = nullptr;
+    if (captureResults.buffer->lock(GraphicBuffer::USAGE_SW_READ_OFTEN,
+                                    reinterpret_cast<void**>(&pixels)) != NO_ERROR ||
+        pixels == nullptr) {
+        ALOGE("Unable to map the capture buffer");
+        return false;
+    }
+    callback(context, pixels, captureResults.buffer->getWidth(),
+             captureResults.buffer->getHeight(), captureResults.buffer->getStride());
+    captureResults.buffer->unlock();
+    return true;
+}
diff --git a/aidl/als/capture.h b/aidl/als/capture.h
new file mode 100644
index 00000000..276dd15d
--- /dev/null
+++ b/aidl/als/capture.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2024 The LineageOS Project
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+#pragma once
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+    int32_t left;
+    int32_t top;
+    int32_t right;
+    int32_t bottom;
+} AlsRect;
+
+typedef struct {
+    // Resolution of the largest display mode.
+    int32_t panel_width;
+    int32_t panel_height;
+    int32_t layer_stack_width;
+    int32_t layer_stack_height;
+    // ui::Rotation of the layer stack relative to the panel, 0-3.
+    int32_t rotation;
+} AlsDisplayGeometry;
+
+// Called with the locked RGBA_8888 capture; stride is in pixels.
+typedef void (*AlsPixelsCallback)(void* context, const uint8_t* pixels, uint32_t width,
+                                  uint32_t height, uint32_t stride);
+
+bool als_get_display_geometry(AlsDisplayGeometry* out);
+bool als_capture(const AlsRect* crop, int32_t width, int32_t height, AlsPixelsCallback callback,
+                 void* context);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/aidl/als/capture_listener.h b/aidl/als/capture_listener.h
new file mode 100644
index 00000000..50d23faa
--- /dev/null
+++ b/aidl/als/capture_listener.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2026 The LineageOS Project
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+#pragma once
+
+#include <android/gui/BnScreenCaptureListener.h>
+#include <chrono>
+#include <condition_variable>
+#include <mutex>
+#include <optional>
+
+// Capture completion is asynchronous. Never leave an incoming ALS call occupying a
+// Binder thread forever if SurfaceFlinger or the callback pool cannot make progress.
+class AlsCaptureListener : public android::gui::BnScreenCaptureListener {
+  public:
+    android::binder::Status onScreenCaptureCompleted(
+            const android::gui::ScreenCaptureResults& results) override {
+        std::lock_guard lock(mMutex);
+        if (!mResults) mResults = results;
+        mReady.notify_one();
+        return android::binder::Status::ok();
+    }
+
+    bool waitForResults(android::gui::ScreenCaptureResults* results,
+                        std::chrono::milliseconds timeout = std::chrono::seconds(2)) {
+        std::unique_lock lock(mMutex);
+        if (!mReady.wait_for(lock, timeout, [this] { return mResults.has_value(); })) {
+            return false;
+        }
+        *results = *mResults;
+        return true;
+    }
+
+  private:
+    std::mutex mMutex;
+    std::condition_variable mReady;
+    std::optional<android::gui::ScreenCaptureResults> mResults;
+};
diff --git a/aidl/als/capture_listener_test.cpp b/aidl/als/capture_listener_test.cpp
new file mode 100644
index 00000000..ef1dad3b
--- /dev/null
+++ b/aidl/als/capture_listener_test.cpp
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2026 The LineageOS Project
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+#include "capture_listener.h"
+#include <gtest/gtest.h>
+
+TEST(AlsCaptureListener, MissingCallbackTimesOut) {
+    AlsCaptureListener listener;
+    android::gui::ScreenCaptureResults results;
+    EXPECT_FALSE(listener.waitForResults(&results, std::chrono::milliseconds(10)));
+}
+
+TEST(AlsCaptureListener, CompletedCaptureDoesNotWaitForAnotherCallback) {
+    AlsCaptureListener listener;
+    android::gui::ScreenCaptureResults sent, received;
+    ASSERT_TRUE(listener.onScreenCaptureCompleted(sent).isOk());
+    EXPECT_TRUE(listener.waitForResults(&received, std::chrono::milliseconds(0)));
+}
+
+TEST(AlsCaptureListener, LateCallbackIsSafeAfterTimeout) {
+    AlsCaptureListener listener;
+    android::gui::ScreenCaptureResults sent, received;
+    ASSERT_FALSE(listener.waitForResults(&received, std::chrono::milliseconds(0)));
+    ASSERT_TRUE(listener.onScreenCaptureCompleted(sent).isOk());
+    EXPECT_TRUE(listener.waitForResults(&received, std::chrono::milliseconds(0)));
+}
diff --git a/aidl/als/main.rs b/aidl/als/main.rs
new file mode 100644
index 00000000..12ee4407
--- /dev/null
+++ b/aidl/als/main.rs
@@ -0,0 +1,292 @@
+/*
+ * Copyright (C) 2021-2024 The LineageOS Project
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+//! Screen area capture for the ALS correction: reports the average color of the screen above
+//! the light sensor.
+
+// The test build has no caller for main() and the service type.
+#![cfg_attr(test, allow(dead_code))]
+
+mod area;
+
+use area::{average_rgb, capture_crop, parse_grab_rect, parse_weights, Geometry, Rect, Weighting};
+use binder::{BinderFeatures, Interface, Status};
+use log::{error, info, warn, LevelFilter};
+use std::ffi::c_void;
+use std::panic::{catch_unwind, AssertUnwindSafe};
+use std::sync::Mutex;
+use vendor_lineage_oplus_als::aidl::vendor::lineage::oplus_als::{
+    AreaRgbCaptureResult::AreaRgbCaptureResult,
+    IAreaCapture::{BnAreaCapture, IAreaCapture},
+};
+
+const LOG_TAG: &str = "vendor.lineage.oplus_als.service";
+const GRAB_RECT_PROP: &str = "vendor.sensors.als_correction.grabrect";
+const WEIGHTS_PATH: &str = "/odm/etc/display/cwb_weightspos.json";
+
+// capture.h
+#[repr(C)]
+struct AlsRect {
+    left: i32,
+    top: i32,
+    right: i32,
+    bottom: i32,
+}
+
+#[repr(C)]
+#[derive(Default)]
+struct AlsDisplayGeometry {
+    panel_width: i32,
+    panel_height: i32,
+    layer_stack_width: i32,
+    layer_stack_height: i32,
+    rotation: i32,
+}
+
+type AlsPixelsCallback = unsafe extern "C" fn(*mut c_void, *const u8, u32, u32, u32);
+
+extern "C" {
+    fn als_get_display_geometry(out: *mut AlsDisplayGeometry) -> bool;
+    fn als_capture(
+        crop: *const AlsRect,
+        width: i32,
+        height: i32,
+        callback: AlsPixelsCallback,
+        context: *mut c_void,
+    ) -> bool;
+}
+
+fn display_geometry() -> Option<Geometry> {
+    let mut g = AlsDisplayGeometry::default();
+    // SAFETY: `g` is a valid, writable AlsDisplayGeometry.
+    if !unsafe { als_get_display_geometry(&mut g) } {
+        return None;
+    }
+    Some(Geometry {
+        panel_width: g.panel_width,
+        panel_height: g.panel_height,
+        layer_stack_width: g.layer_stack_width,
+        layer_stack_height: g.layer_stack_height,
+        rotation: g.rotation,
+    })
+}
+
+struct CaptureJob<'a> {
+    width: i32,
+    height: i32,
+    weighting: Option<Weighting<'a>>,
+    result: Option<[f32; 3]>,
+}
+
+unsafe extern "C" fn on_pixels(
+    context: *mut c_void,
+    pixels: *const u8,
+    width: u32,
+    height: u32,
+    stride: u32,
+) {
+    // SAFETY: `context` is the CaptureJob that capture() passes to als_capture, which only
+    // calls back before returning.
+    let job = unsafe { &mut *context.cast::<CaptureJob>() };
+    let len = (stride as usize)
+        .checked_mul(height as usize)
+        .and_then(|n| n.checked_mul(4));
+    let (Some(len), false) = (
+        len,
+        pixels.is_null() || stride < width || len.is_some_and(|n| n > isize::MAX as usize),
+    ) else {
+        return;
+    };
+    // SAFETY: the shim passes the locked RGBA_8888 buffer, which holds stride * height pixels
+    // and stays mapped until this callback returns.
+    let pixels = unsafe { std::slice::from_raw_parts(pixels, len) };
+
+    // Weights apply only if the capture came back at the requested one pixel per panel pixel.
+    let weighting = job
+        .weighting
+        .as_ref()
+        .filter(|_| i64::from(width) == i64::from(job.width))
+        .filter(|_| i64::from(height) == i64::from(job.height));
+    // Never unwind into C++.
+    job.result = catch_unwind(AssertUnwindSafe(|| {
+        average_rgb(pixels, width, height, stride, weighting)
+    }))
+    .ok()
+    .flatten();
+}
+
+fn capture(crop: &Rect, mut job: CaptureJob) -> Option<[f32; 3]> {
+    let crop = AlsRect {
+        left: crop.left,
+        top: crop.top,
+        right: crop.right,
+        bottom: crop.bottom,
+    };
+    // SAFETY: `crop` and `job` outlive the call, and on_pixels matches AlsPixelsCallback.
+    let captured = unsafe {
+        als_capture(
+            &crop,
+            job.width,
+            job.height,
+            on_pixels,
+            (&mut job as *mut CaptureJob).cast::<c_void>(),
+        )
+    };
+    if captured {
+        job.result
+    } else {
+        None
+    }
+}
+
+fn load_weights(rect: &Rect) -> Vec<f32> {
+    let Ok(json) = std::fs::read_to_string(WEIGHTS_PATH) else {
+        return Vec::new();
+    };
+    let count = (rect.width() as usize) * (rect.height() as usize);
+    match parse_weights(&json, count) {
+        Ok(weights) => {
+            info!("Loaded {} grab area weights", weights.len());
+            weights
+        }
+        Err(e) => {
+            warn!("{WEIGHTS_PATH} {e}; using unweighted sampling");
+            Vec::new()
+        }
+    }
+}
+
+struct AreaCapture {
+    capture_lock: Mutex<()>,
+    rect: Option<Rect>,
+    // Per-pixel weights of the grab area in panel orientation, row major.
+    weights: Vec<f32>,
+}
+
+impl AreaCapture {
+    fn new() -> Self {
+        let value = rustutils::android::system_properties::read(GRAB_RECT_PROP)
+            .ok()
+            .flatten();
+        let Some(rect) = value.as_deref().and_then(parse_grab_rect) else {
+            error!("No valid screenshot grab area config");
+            return Self {
+                capture_lock: Mutex::new(()),
+                rect: None,
+                weights: Vec::new(),
+            };
+        };
+        info!(
+            "Screenshot grab area: {} {} {} {}",
+            rect.left, rect.top, rect.right, rect.bottom
+        );
+        Self {
+            capture_lock: Mutex::new(()),
+            rect: Some(rect),
+            weights: load_weights(&rect),
+        }
+    }
+}
+
+fn failed() -> Status {
+    Status::new_service_specific_error(-1, None)
+}
+
+impl Interface for AreaCapture {}
+
+#[allow(non_snake_case)]
+impl IAreaCapture for AreaCapture {
+    fn getAreaBrightness(&self) -> binder::Result<AreaRgbCaptureResult> {
+        // Never occupy another Binder thread waiting behind an in-flight capture:
+        // screenshot completion must be able to enter this same process.
+        let _capture = self.capture_lock.try_lock().map_err(|_| failed())?;
+        let Some(rect) = self.rect else {
+            return Err(failed());
+        };
+        let Some((geometry, crop)) =
+            display_geometry().and_then(|g| Some((g, capture_crop(&rect, &g)?)))
+        else {
+            error!("Unable to map the grab area to the display");
+            return Err(failed());
+        };
+
+        // Weighted captures are scaled back to one pixel per panel pixel, in layer stack
+        // orientation.
+        let transposed = matches!(geometry.rotation, 1 | 3);
+        let (width, height) = match (self.weights.is_empty(), transposed) {
+            (true, _) => (crop.width(), crop.height()),
+            (false, false) => (rect.width(), rect.height()),
+            (false, true) => (rect.height(), rect.width()),
+        };
+        let weighting = (!self.weights.is_empty()).then(|| Weighting {
+            weights: &self.weights,
+            rotation: geometry.rotation,
+            panel_width: rect.width(),
+            panel_height: rect.height(),
+        });
+
+        let [r, g, b] = capture(
+            &crop,
+            CaptureJob {
+                width,
+                height,
+                weighting,
+                result: None,
+            },
+        )
+        .ok_or_else(failed)?;
+        Ok(AreaRgbCaptureResult { r, g, b })
+    }
+}
+
+fn main() {
+    logger::init(
+        logger::Config::default()
+            .with_tag_on_device(LOG_TAG)
+            .with_max_level(LevelFilter::Info),
+    );
+
+    // Capture completion uses the same Binder pool. Leave callback capacity when the
+    // sensor HAL and diagnostic clients request samples concurrently. The shim also
+    // bounds callback/fence waits so saturation cannot hang the service permanently.
+    binder::ProcessState::set_thread_pool_max_thread_count(4);
+    binder::ProcessState::start_thread_pool();
+
+    let service = BnAreaCapture::new_binder(AreaCapture::new(), BinderFeatures::default());
+    let instance = format!(
+        "{}/default",
+        <AreaCapture as IAreaCapture>::get_descriptor()
+    );
+    binder::add_service(&instance, service.as_binder()).expect("Failed to register service");
+
+    binder::ProcessState::join_thread_pool();
+}
+
+#[cfg(test)]
+mod callback_tests {
+    use super::*;
+
+    #[test]
+    fn callback_validates_layout_and_returns_rgb() {
+        let mut job = CaptureJob {
+            width: 2,
+            height: 1,
+            weighting: None,
+            result: None,
+        };
+        let context = (&mut job as *mut CaptureJob).cast::<c_void>();
+        let pixels = [255u8; 8];
+        // SAFETY: context and pixels stay valid for each synchronous call.
+        unsafe { on_pixels(context, pixels.as_ptr(), 2, 1, 1) };
+        assert!(job.result.is_none());
+        unsafe { on_pixels(context, std::ptr::null(), 2, 1, 2) };
+        assert!(job.result.is_none());
+        unsafe { on_pixels(context, pixels.as_ptr(), 2, 1, 2) };
+        for value in job.result.unwrap() {
+            assert!((value - 255.0).abs() < 1e-3);
+        }
+    }
+}
