A hardened Linux desktop, rebuilt from scratch, with your Windows apps built in. Free and open source.
Description: Goodix 27c6:533c reader (Dell XPS 13 9300 and 9310)
The goodix53x5 driver from seaweeduk/goodix53x5-libfprint pull request
334, commit 52584a593d29e1cf8b317f53cb46c54396a3e4f1 (LGPL-2.1-or-later),
with only its 533c (GM168SEC) family. Wild OS changes: the 5335/5385/5395
family, which writes a PSK to the sensor, is left out with the PSK write
command; the 533c family sends only an allow-list of read and RAM-only
commands; firmware in its bootloader is refused; the update-result calls
use stock libfprint 1.94.9 API; CRC-32 is computed locally instead of with
libdeflate; three matcher guards (a loop bound, INT64_MIN / -1, zeroed
results) and a divide-by-zero guard. 533c moves from the unsupported list
to the driver's hwdb section. The driver's matcher unit tests are added.
Origin: https://github.com/seaweeduk/goodix53x5-libfprint/pull/334
Forwarded: not-needed
---
diff --git a/data/autosuspend.hwdb b/data/autosuspend.hwdb
index 9115fb0..816f3c7 100644
--- a/data/autosuspend.hwdb
+++ b/data/autosuspend.hwdb
@@ -193,6 +193,11 @@ usb:v10A5pC844*
ID_AUTOSUSPEND=1
ID_PERSIST=0
+# Supported by libfprint driver goodix53x5
+usb:v27C6p533C*
+ ID_AUTOSUSPEND=1
+ ID_PERSIST=0
+
# Supported by libfprint driver goodixmoc
usb:v27C6p5840*
usb:v27C6p6014*
@@ -440,7 +445,6 @@ usb:v27C6p5301*
usb:v27C6p530C*
usb:v27C6p532D*
usb:v27C6p5335*
-usb:v27C6p533C*
usb:v27C6p5381*
usb:v27C6p5385*
usb:v27C6p538C*
diff --git a/libfprint/drivers/goodix53x5/device/auth.c b/libfprint/drivers/goodix53x5/device/auth.c
new file mode 100644
index 0000000..d9b75bf
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/auth.c
@@ -0,0 +1,697 @@
+/*
+ * Goodix 53x5 driver for libfprint - native Milan verify/identify flow
+ * Copyright (C) 2024-2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "fpi-print.h"
+#include "device/auth.h"
+#include "milan/print.h"
+#include "driver-private.h"
+#include "milan/runtime.h"
+#include "device/persistence.h"
+#include "device/scan.h"
+#include "device/session.h"
+
+typedef enum
+{
+ GOODIX_VERIFY_REINIT = 0,
+ GOODIX_VERIFY_REINIT_DONE,
+ GOODIX_VERIFY_SCAN,
+ GOODIX_VERIFY_FINISH,
+ GOODIX_VERIFY_NUM_STATES,
+} GoodixVerifyState;
+
+typedef struct
+{
+ GoodixMilanRuntimeInput *runtime_input;
+ GPtrArray *originals;
+ FpiDeviceAction action;
+ guint64 action_epoch;
+ guint64 generation_id;
+ GOODIX53X5_DEBUG_ONLY (GoodixDebugRuntimeMetadata debug_metadata;)
+} GoodixAuthTaskData;
+
+#ifdef GOODIX53X5_DEBUG
+static const gchar *
+goodix_auth_finger_name (FpFinger finger)
+{
+ static const gchar * const names[] = {
+ "unknown", "left-thumb", "left-index", "left-middle", "left-ring",
+ "left-little", "right-thumb", "right-index", "right-middle",
+ "right-ring", "right-little"
+ };
+
+ return (guint) finger < G_N_ELEMENTS (names) ? names[finger] : "unknown";
+}
+
+static void
+goodix_auth_log_runtime_result (FpDevice *dev,
+ GoodixAuthTaskData *data,
+ const GoodixMilanRuntimeOutput *output,
+ gboolean driver_cancellation_observed)
+{
+ goodix_debug_log_runtime_result (dev, 0, &data->debug_metadata, output,
+ driver_cancellation_observed);
+}
+#else
+#define goodix_auth_log_runtime_result(...) G_STMT_START { } G_STMT_END
+#endif
+
+static void
+goodix_auth_print_unref (gpointer object)
+{
+ if (object)
+ g_object_unref (object);
+}
+
+static void
+goodix_auth_task_data_free (GoodixAuthTaskData *data)
+{
+ if (!data)
+ return;
+ goodix_milan_runtime_input_free (data->runtime_input);
+ GOODIX53X5_DEBUG_ONLY (
+ goodix_debug_clear_runtime_metadata (&data->debug_metadata);)
+ g_clear_pointer (&data->originals, g_ptr_array_unref);
+ g_free (data);
+}
+
+void
+goodix_clear_pending_result_report (FpiDeviceGoodix53x5 *self)
+{
+ self->pending_result_report = FALSE;
+ self->pending_result_action = 0;
+ self->pending_verify_result = 0;
+ g_clear_object (&self->pending_identify_match);
+ g_clear_object (&self->pending_update_target);
+ g_clear_pointer (&self->pending_update_data, g_variant_unref);
+ g_clear_pointer (&self->pending_persistence_state, g_free);
+ g_clear_error (&self->pending_result_error);
+ g_clear_error (&self->pending_learning_error);
+}
+
+static void
+goodix_queue_verify_report (FpiDeviceGoodix53x5 *self,
+ FpiMatchResult result,
+ GError *error)
+{
+ goodix_clear_pending_result_report (self);
+ self->pending_result_report = TRUE;
+ self->pending_result_action = FPI_DEVICE_ACTION_VERIFY;
+ self->pending_verify_result = result;
+ self->pending_result_error = error;
+}
+
+static void
+goodix_queue_identify_report (FpiDeviceGoodix53x5 *self,
+ FpPrint *match,
+ GError *error)
+{
+ goodix_clear_pending_result_report (self);
+ self->pending_result_report = TRUE;
+ self->pending_result_action = FPI_DEVICE_ACTION_IDENTIFY;
+ if (match)
+ self->pending_identify_match = g_object_ref (match);
+ self->pending_result_error = error;
+}
+
+static void
+goodix_flush_pending_result_report (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ g_autoptr(GError) learning_error = NULL;
+
+ if (!self->pending_result_report)
+ return;
+
+ self->pending_result_report = FALSE;
+ learning_error = g_steal_pointer (&self->pending_learning_error);
+ if (learning_error)
+ fp_warn ("Native Milan learning was discarded after a positive match: %s",
+ learning_error->message);
+
+ if (self->pending_result_action == FPI_DEVICE_ACTION_IDENTIFY)
+ fpi_device_identify_report (
+ dev, self->pending_identify_match, NULL,
+ g_steal_pointer (&self->pending_result_error));
+ else
+ fpi_device_verify_report (
+ dev, self->pending_verify_result, NULL,
+ g_steal_pointer (&self->pending_result_error));
+}
+
+static gboolean
+goodix_auth_runtime_cancelled (GoodixMilanRuntimeCheckpoint checkpoint,
+ gsize gallery_position,
+ gpointer user_data)
+{
+ (void) checkpoint;
+ (void) gallery_position;
+ return g_cancellable_is_cancelled (G_CANCELLABLE (user_data));
+}
+
+static gboolean
+goodix_auth_get_template (FpPrint *print,
+ GBytes **template_bytes,
+ GError **error)
+{
+ g_autoptr(GVariant) data = NULL;
+ FpiPrintType type;
+
+ g_object_get (print, "fpi-type", &type, "fpi-data", &data, NULL);
+ if (type != FPI_PRINT_RAW)
+ {
+ g_set_error_literal (error, GOODIX_MILAN_PRINT_ERROR,
+ GOODIX_MILAN_PRINT_ERROR_INCOMPATIBLE,
+ "Native Milan requires a raw runtime print");
+ return FALSE;
+ }
+ return goodix_milan_print_parse_data (data, template_bytes, error);
+}
+
+static void
+goodix_auth_worker (GTask *task,
+ gpointer source_object,
+ gpointer task_data,
+ GCancellable *cancellable)
+{
+ GoodixAuthTaskData *data = task_data;
+ GoodixMilanRuntimeOutput *output;
+
+ (void) source_object;
+ (void) cancellable;
+ output = goodix_milan_runtime_run (data->runtime_input);
+ g_task_return_pointer (task, output,
+ (GDestroyNotify) goodix_milan_runtime_output_free);
+}
+
+static GVariant *
+goodix_auth_build_update (GoodixMilanRuntimeOutput *output)
+{
+ g_autoptr(GError) error = NULL;
+ g_autoptr(GVariant) data = NULL;
+
+ if (!output->final_candidate)
+ return NULL;
+ data = goodix_milan_print_build_data (output->final_candidate, &error);
+ if (!data)
+ {
+ if (!output->learning_error)
+ output->learning_error = g_steal_pointer (&error);
+ return NULL;
+ }
+ return g_steal_pointer (&data);
+}
+
+#ifdef GOODIX53X5_DEBUG
+static void
+goodix_auth_set_processed_image (FpiDeviceGoodix53x5 *self,
+ GoodixMilanRuntimeOutput *output)
+{
+ const guint8 *image;
+ gsize size;
+
+ g_clear_pointer (&self->captured_image, g_free);
+ image = output->processed_image
+ ? g_bytes_get_data (output->processed_image, &size) : NULL;
+ if (image && size == GOODIX_SENSOR_PIXELS)
+ self->captured_image = g_memdup2 (image, size);
+}
+#endif
+
+static void
+goodix_auth_task_done (GObject *source_object,
+ GAsyncResult *result,
+ gpointer user_data)
+{
+ FpDevice *dev = FP_DEVICE (source_object);
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixAuthTaskData *data = g_task_get_task_data (G_TASK (result));
+ g_autoptr(GError) task_error = NULL;
+ GoodixMilanRuntimeOutput *output = g_task_propagate_pointer (
+ G_TASK (result), &task_error);
+ gboolean task_owned;
+ gboolean same_action;
+ gboolean action_owned;
+ gboolean generation_current;
+ gboolean cancelled;
+ gboolean matched = FALSE;
+ GOODIX53X5_DEBUG_ONLY (const gchar *finger_name = "none";)
+ GOODIX53X5_DEBUG_ONLY (FpPrint *winner_print = NULL;)
+ GOODIX53X5_DEBUG_ONLY (g_autofree gchar *template_features = NULL;)
+ GOODIX53X5_DEBUG_ONLY (g_autofree gchar *winner = NULL;)
+
+ (void) user_data;
+ task_owned = self->milan_task == G_TASK (result);
+ same_action = task_owned &&
+ fpi_device_get_current_action (dev) == data->action;
+ cancelled = same_action &&
+ (fpi_device_action_is_cancelled (dev) ||
+ !self->cancel || g_cancellable_is_cancelled (self->cancel) ||
+ (output && output->status == GOODIX_MILAN_RUNTIME_CANCELLED) ||
+ (task_error && g_error_matches (task_error, G_IO_ERROR,
+ G_IO_ERROR_CANCELLED)));
+ action_owned = same_action &&
+ (self->action_epoch == data->action_epoch || cancelled);
+ generation_current = action_owned && self->milan_generation &&
+ self->milan_generation->generation_id ==
+ data->generation_id;
+ if (task_owned)
+ g_clear_object (&self->milan_task);
+
+ if (!action_owned)
+ {
+ if (output)
+ goodix_auth_log_runtime_result (dev, data, output, FALSE);
+ goodix_milan_runtime_output_free (output);
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ if (task_owned && self->profile9_fdt.owner)
+ goodix_scan_set_disposition (dev, GOODIX_SCAN_DISPOSITION_CANCELLED,
+ NULL);
+ return;
+ }
+
+ if (generation_current && output &&
+ output->action_epoch == data->action_epoch &&
+ output->generation_id == data->generation_id &&
+ output->preprocess_state_valid && !cancelled)
+ {
+ self->milan_generation->state = output->preprocess_state;
+ self->milan_generation->profile_state = output->profile_state;
+ if (data->action == FPI_DEVICE_ACTION_IDENTIFY)
+ goodix_milan_generation_note_identify_prelude (self->milan_generation);
+ }
+ else if (generation_current && output &&
+ output->action_epoch == data->action_epoch &&
+ output->generation_id == data->generation_id &&
+ output->setup_state_valid)
+ {
+ /* Setup-save has already happened, even if cancellation discards live
+ * processing. Preserve only its three flags, not cancelled gain changes. */
+ self->milan_generation->profile_state.setup_initialized =
+ output->profile_state.setup_initialized;
+ self->milan_generation->profile_state.setup_refresh_pending =
+ output->profile_state.setup_refresh_pending;
+ self->milan_generation->profile_state.setup_not_ready =
+ output->profile_state.setup_not_ready;
+ }
+
+ if (cancelled)
+ {
+ if (output)
+ goodix_auth_log_runtime_result (dev, data, output, TRUE);
+ goodix_milan_runtime_output_free (output);
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ goodix_scan_set_disposition (dev, GOODIX_SCAN_DISPOSITION_CANCELLED,
+ NULL);
+ return;
+ }
+
+ if (!output || task_error ||
+ output->action_epoch != data->action_epoch ||
+ output->generation_id != data->generation_id)
+ {
+ goodix_milan_runtime_output_free (output);
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_FATAL,
+ task_error ? g_steal_pointer (&task_error)
+ : fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_GENERAL,
+ "Native Milan auth task returned invalid output"));
+ return;
+ }
+
+ GOODIX53X5_DEBUG_ONLY (goodix_auth_set_processed_image (self, output);)
+ switch (output->status)
+ {
+ case GOODIX_MILAN_RUNTIME_MATCH:
+ {
+ FpPrint *original = output->winner_index < data->originals->len
+ ? g_ptr_array_index (data->originals,
+ output->winner_index)
+ : NULL;
+ g_autoptr(GVariant) update_data = NULL;
+
+ if (!original)
+ {
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_FATAL,
+ fpi_device_error_new (FP_DEVICE_ERROR_DATA_INVALID));
+ goto out;
+ }
+ update_data = goodix_auth_build_update (output);
+ if (data->action == FPI_DEVICE_ACTION_IDENTIFY)
+ {
+ goodix_debug_dump_probe (data->action, "match",
+ self->captured_raw_image,
+ self->captured_image);
+ goodix_queue_identify_report (self, original, NULL);
+ }
+ else
+ {
+ goodix_debug_dump_probe (data->action, "pass",
+ self->captured_raw_image,
+ self->captured_image);
+ goodix_queue_verify_report (self, FPI_MATCH_SUCCESS, NULL);
+ }
+ if (update_data)
+ {
+ self->pending_update_target = g_object_ref (original);
+ self->pending_update_data = g_steal_pointer (&update_data);
+ if (output->preprocess_state_valid)
+ self->pending_persistence_state = g_memdup2 (
+ &output->preprocess_state, sizeof (output->preprocess_state));
+ }
+ if (output->learning_error)
+ self->pending_learning_error = g_error_copy (output->learning_error);
+ matched = TRUE;
+ }
+ break;
+
+ case GOODIX_MILAN_RUNTIME_NO_MATCH:
+ if (data->action == FPI_DEVICE_ACTION_IDENTIFY)
+ {
+ goodix_debug_dump_probe (data->action, "miss",
+ self->captured_raw_image,
+ self->captured_image);
+ goodix_queue_identify_report (self, NULL, NULL);
+ }
+ else
+ {
+ goodix_debug_dump_probe (data->action, "fail",
+ self->captured_raw_image,
+ self->captured_image);
+ goodix_queue_verify_report (self, FPI_MATCH_FAIL, NULL);
+ }
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_AUTH_RETRY_AFTER_UP, NULL);
+ break;
+
+ case GOODIX_MILAN_RUNTIME_RETRY:
+ goodix_debug_dump_probe (data->action, "weak",
+ self->captured_raw_image,
+ self->captured_image);
+ if (data->action == FPI_DEVICE_ACTION_IDENTIFY)
+ goodix_queue_identify_report (
+ self, NULL,
+ fpi_device_retry_new (FP_DEVICE_RETRY_REMOVE_FINGER));
+ else
+ goodix_queue_verify_report (
+ self, FPI_MATCH_ERROR,
+ fpi_device_retry_new (FP_DEVICE_RETRY_REMOVE_FINGER));
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_AUTH_RETRY_AFTER_UP, NULL);
+ break;
+
+ case GOODIX_MILAN_RUNTIME_INVALID_DATA:
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_FATAL,
+ fpi_device_error_new (FP_DEVICE_ERROR_DATA_INVALID));
+ break;
+
+ case GOODIX_MILAN_RUNTIME_CANCELLED:
+ g_assert_not_reached ();
+ }
+
+ goodix_auth_log_runtime_result (dev, data, output, FALSE);
+ GOODIX53X5_DEBUG_ONLY (
+ winner = goodix_debug_format_winner (output->winner_index,
+ output->winner_position);
+ template_features = goodix_debug_format_template_features (output);
+ if (output->winner_index < data->originals->len)
+ winner_print = g_ptr_array_index (data->originals, output->winner_index);
+ if (winner_print)
+ finger_name = goodix_auth_finger_name (
+ fp_print_get_finger (winner_print));
+
+ fp_dbg ("Native Milan %s status=%s(%u) score=%d finger=%s winner=%s "
+ "study=%s(%u) template_features=%s quality=%d coverage=%d",
+ data->action == FPI_DEVICE_ACTION_IDENTIFY ? "identify" : "verify",
+ goodix_debug_runtime_status_name (output->status),
+ (guint) output->status, output->score, finger_name, winner,
+ goodix_debug_study_action_name (output->study_action),
+ (guint) output->study_action,
+ template_features, output->quality, output->coverage);)
+out:
+ goodix_milan_runtime_output_free (output);
+#ifdef GOODIX53X5_DEBUG
+ g_clear_pointer (&self->captured_image, g_free);
+#endif
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ /* The coordinator hands the action back as soon as this join settles;
+ * the report itself is delivered by goodix_verify_complete. */
+ if (matched)
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_AUTH_SUCCESS, NULL);
+}
+
+static void
+goodix_auth_start_task (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ FpiDeviceAction action = fpi_device_get_current_action (dev);
+ g_autoptr(GPtrArray) runtime_gallery = g_ptr_array_new_with_free_func (
+ (GDestroyNotify) goodix_milan_runtime_gallery_input_free);
+ GoodixAuthTaskData *task_data = g_new0 (GoodixAuthTaskData, 1);
+ GPtrArray *gallery = NULL;
+ guint invalid_count = 0;
+
+ task_data->action = action;
+ task_data->action_epoch = self->action_epoch;
+ if (!self->milan_generation || !self->captured_raw_image || self->milan_task)
+ {
+ goodix_auth_task_data_free (task_data);
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_FATAL,
+ fpi_device_error_new_msg (FP_DEVICE_ERROR_GENERAL,
+ "Native Milan auth input is missing or busy"));
+ return;
+ }
+ task_data->generation_id = self->milan_generation->generation_id;
+ GOODIX53X5_DEBUG_ONLY (
+ goodix_debug_capture_runtime_metadata (
+ &task_data->debug_metadata, action,
+ self->milan_generation->setup_tx_on, self->captured_raw_image,
+ self->milan_generation->use_count,
+ self->milan_generation->profile_state.setup_initialized,
+ self->milan_generation->profile_state.setup_refresh_pending,
+ self->milan_generation->profile_state.setup_not_ready);)
+
+ if (action == FPI_DEVICE_ACTION_VERIFY)
+ {
+ FpPrint *print = NULL;
+ g_autoptr(GBytes) template_bytes = NULL;
+ g_autoptr(GError) error = NULL;
+
+ task_data->originals = g_ptr_array_new_with_free_func (
+ goodix_auth_print_unref);
+ fpi_device_get_verify_data (dev, &print);
+ if (!goodix_auth_get_template (print, &template_bytes, &error))
+ {
+ goodix_auth_task_data_free (task_data);
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_FATAL,
+ fpi_device_error_new (FP_DEVICE_ERROR_DATA_INVALID));
+ return;
+ }
+ g_ptr_array_add (task_data->originals, g_object_ref (print));
+ g_ptr_array_add (runtime_gallery,
+ goodix_milan_runtime_gallery_input_new (0, template_bytes));
+ }
+ else
+ {
+ fpi_device_get_identify_data (dev, &gallery);
+ task_data->originals = g_ptr_array_new_with_free_func (
+ goodix_auth_print_unref);
+ g_ptr_array_set_size (task_data->originals, gallery->len);
+ for (guint i = 0; i < gallery->len; i++)
+ {
+ FpPrint *print = g_ptr_array_index (gallery, i);
+ g_autoptr(GBytes) template_bytes = NULL;
+ g_autoptr(GError) error = NULL;
+
+ if (!goodix_auth_get_template (print, &template_bytes, &error))
+ {
+ invalid_count++;
+ fp_warn ("Skipping invalid Milan identify gallery entry %u", i);
+ continue;
+ }
+ task_data->originals->pdata[i] = g_object_ref (print);
+ g_ptr_array_add (runtime_gallery,
+ goodix_milan_runtime_gallery_input_new (
+ i, template_bytes));
+ }
+ if (gallery->len > 0 && runtime_gallery->len == 0 && invalid_count > 0)
+ {
+ goodix_auth_task_data_free (task_data);
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_FATAL,
+ fpi_device_error_new (FP_DEVICE_ERROR_DATA_INVALID));
+ return;
+ }
+ }
+
+ task_data->runtime_input = goodix_milan_runtime_input_new (
+ task_data->action_epoch, task_data->generation_id,
+ GOODIX_MILAN_PURPOSE_IDENTIFY, &self->milan_generation->state,
+ &self->milan_generation->profile_state,
+ self->milan_generation->setup_tx_on, self->captured_raw_image,
+ self->calib.tcode, self->calib.dac_h, self->calib.dac_l,
+ self->milan_sensor_subtype,
+ (GoodixMilanRuntimeGalleryInput *const *) runtime_gallery->pdata,
+ runtime_gallery->len);
+ if (!task_data->runtime_input)
+ {
+ goodix_auth_task_data_free (task_data);
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_FATAL,
+ fpi_device_error_new (FP_DEVICE_ERROR_GENERAL));
+ return;
+ }
+ goodix_milan_persistence_bind_setup (task_data->runtime_input,
+ self->milan_generation);
+ goodix_milan_runtime_input_set_capture_health (task_data->runtime_input,
+ self->captured_enroll_allowed);
+ goodix_milan_runtime_input_set_cancel_check (
+ task_data->runtime_input, goodix_auth_runtime_cancelled,
+ g_object_ref (self->cancel), g_object_unref);
+ g_autoptr(GTask) task = g_task_new (dev, self->cancel,
+ goodix_auth_task_done, NULL);
+ /* Runtime cancellation still suppresses results. Keep the joined output so
+ * an entered setup publication can retain its independent state flags. */
+ g_task_set_check_cancellable (task, FALSE);
+ g_task_set_task_data (task, task_data,
+ (GDestroyNotify) goodix_auth_task_data_free);
+ self->milan_task = g_object_ref (task);
+ g_task_run_in_thread (task, goodix_auth_worker);
+}
+
+static void
+goodix_auth_capture_ready (FpDevice *dev,
+ gpointer user_data)
+{
+ (void) user_data;
+ goodix_auth_start_task (dev);
+}
+
+static void
+goodix_verify_ssm_handler (FpiSsm *ssm,
+ FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ switch (fpi_ssm_get_cur_state (ssm))
+ {
+ case GOODIX_VERIFY_REINIT:
+ if (!goodix_maybe_start_reinit_subsm (ssm, dev))
+ fpi_ssm_next_state (ssm);
+ break;
+ case GOODIX_VERIFY_REINIT_DONE:
+ goodix_debug_timing_open_done (self, dev, "reinit");
+ self->needs_reinit = FALSE;
+ fpi_ssm_next_state (ssm);
+ break;
+ case GOODIX_VERIFY_SCAN:
+ goodix_scan_start_coordinator_subsm (
+ ssm, dev, goodix_auth_capture_ready, NULL, NULL);
+ break;
+ case GOODIX_VERIFY_FINISH:
+ fpi_ssm_mark_completed (ssm);
+ break;
+ case GOODIX_VERIFY_NUM_STATES:
+ g_assert_not_reached ();
+ }
+}
+
+static void
+goodix_verify_complete (FpDevice *dev,
+ GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ FpiDeviceAction action = fpi_device_get_current_action (dev);
+ gboolean updated = FALSE;
+ gboolean removed = FALSE;
+ gboolean cancelled;
+
+#ifdef GOODIX53X5_DEBUG
+ g_clear_pointer (&self->captured_image, g_free);
+#endif
+ g_clear_pointer (&self->captured_raw_image, g_free);
+
+ g_object_get (dev, "removed", &removed, NULL);
+ cancelled = fpi_device_action_is_cancelled (dev) ||
+ (self->cancel && g_cancellable_is_cancelled (self->cancel));
+ if (!error && cancelled)
+ error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_CANCELLED, "Authentication cancelled");
+ if (!error && removed)
+ error = fpi_device_error_new (FP_DEVICE_ERROR_REMOVED);
+ if (!error && !self->pending_result_report)
+ error = fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_GENERAL,
+ "Native Milan auth completed without a result");
+ if (!error)
+ {
+ /* Adaptive update and its persistence publish with the result, before
+ * the application learns of the match. */
+ if (self->pending_update_target && self->pending_update_data)
+ {
+ /* Debian's libfprint has no fpi_print_set_raw_data(); this is
+ * what it does. Stock fprintd does not save the updated print. */
+ g_object_set (self->pending_update_target, "fpi-data",
+ self->pending_update_data, NULL);
+ updated = TRUE;
+ goodix_milan_persistence_save (dev, self->pending_persistence_state);
+ }
+ goodix_flush_pending_result_report (dev);
+ }
+ goodix_clear_pending_result_report (self);
+
+ if (error && goodix_error_indicates_stale_device (error))
+ self->needs_reinit = TRUE;
+ goodix_debug_timing_action_done (self, dev,
+ error ? error->message : NULL);
+ /* The update flag only matters to the upstream project's patched fprintd. */
+ (void) updated;
+ if (action == FPI_DEVICE_ACTION_IDENTIFY)
+ fpi_device_identify_complete (dev, error);
+ else
+ fpi_device_verify_complete (dev, error);
+}
+
+static void
+goodix_verify_ssm_done (FpiSsm *ssm, FpDevice *dev, GError *error)
+{
+ goodix_session_action_done (dev, error, goodix_verify_complete);
+}
+
+void
+goodix_auth_start (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ FpiSsm *ssm;
+
+ g_clear_object (&self->cancel);
+ self->cancel = g_cancellable_new ();
+ goodix_clear_pending_result_report (self);
+ self->action_epoch++;
+ if (self->action_epoch == 0)
+ self->action_epoch++;
+#ifdef GOODIX53X5_DEBUG
+ g_clear_pointer (&self->captured_image, g_free);
+#endif
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ goodix_debug_timing_action_start (self, dev, NULL);
+
+ ssm = fpi_ssm_new (dev, goodix_verify_ssm_handler,
+ GOODIX_VERIFY_NUM_STATES);
+ fpi_ssm_start (ssm, goodix_verify_ssm_done);
+}
diff --git a/libfprint/drivers/goodix53x5/device/auth.h b/libfprint/drivers/goodix53x5/device/auth.h
new file mode 100644
index 0000000..6480cca
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/auth.h
@@ -0,0 +1,31 @@
+/*
+ * Goodix 53x5 driver for libfprint — Verify/identify flow
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#pragma once
+
+#include "driver-private.h"
+
+/* Reset verify/identify action state and run the full auth flow; the shared
+ * SSM dispatches on the current libfprint action. Implements both
+ * FpDeviceClass::verify and FpDeviceClass::identify. */
+void goodix_auth_start (FpDevice *dev);
+
+/* Drop any match result queued while waiting for finger-up. Used by auth
+ * setup and by close to discard stale results. */
+void goodix_clear_pending_result_report (FpiDeviceGoodix53x5 *self);
diff --git a/libfprint/drivers/goodix53x5/device/base.c b/libfprint/drivers/goodix53x5/device/base.c
new file mode 100644
index 0000000..28633e3
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/base.c
@@ -0,0 +1,1076 @@
+/*
+ * Goodix 53x5 driver for libfprint - native Milan base generation
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "device/base.h"
+#include "device/persistence.h"
+
+#include <string.h>
+
+GQuark
+goodix_milan_base_error_quark (void)
+{
+ return g_quark_from_static_string ("goodix-milan-base-error");
+}
+
+gboolean
+goodix_milan_runtime_subtype_for_chip (guint32 chip_id,
+ guint16 *subtype)
+{
+ if ((chip_id & GOODIX_MILAN_PROFILE9_CHIP_FAMILY_MASK) !=
+ GOODIX_MILAN_PROFILE9_CHIP_FAMILY_PREFIX)
+ return FALSE;
+
+ if (subtype)
+ *subtype = GOODIX_MILAN_VALIDATED_SUBTYPE;
+ return TRUE;
+}
+
+gboolean
+goodix_milan_base_pair_mad (const guint16 *tx_on,
+ gsize tx_on_values,
+ const guint16 *tx_off,
+ gsize tx_off_values,
+ guint64 *mad,
+ GError **error)
+{
+ guint64 sum = 0;
+ const gsize rows = GOODIX_MILAN_SENSOR_ROWS;
+ const gsize columns = GOODIX_MILAN_SENSOR_COLUMNS;
+ const gsize count = GOODIX_MILAN_SENSOR_PIXELS;
+ const gsize interior =
+ (rows - 2 * GOODIX_MILAN_BASE_BORDER) *
+ (columns - 2 * GOODIX_MILAN_BASE_BORDER);
+
+ if (!tx_on || !tx_off || tx_on_values != count || tx_off_values != count)
+ {
+ g_set_error_literal (error, GOODIX_MILAN_BASE_ERROR,
+ GOODIX_MILAN_BASE_ERROR_INVALID_FRAME,
+ "Milan base frames must each contain exactly 9504 values");
+ return FALSE;
+ }
+
+ for (gsize row = GOODIX_MILAN_BASE_BORDER;
+ row < rows - GOODIX_MILAN_BASE_BORDER; row++)
+ for (gsize column = GOODIX_MILAN_BASE_BORDER;
+ column < columns - GOODIX_MILAN_BASE_BORDER; column++)
+ {
+ const gsize index = row * columns + column;
+ const guint16 first = tx_on[index];
+ const guint16 second = tx_off[index];
+
+ sum += first >= second ? first - second : second - first;
+ }
+
+ if (mad)
+ *mad = sum / interior;
+ return TRUE;
+}
+
+void
+goodix_milan_base_attempt_init (GoodixMilanBaseAttempt *attempt)
+{
+ g_return_if_fail (attempt != NULL);
+ memset (attempt, 0, sizeof (*attempt));
+}
+
+static void
+goodix_milan_base_attempt_release_frames (GoodixMilanBaseAttempt *attempt)
+{
+ g_clear_pointer (&attempt->tx_on, g_free);
+ g_clear_pointer (&attempt->tx_off, g_free);
+ attempt->tx_on_values = 0;
+ attempt->tx_off_values = 0;
+ attempt->admitted = FALSE;
+}
+
+void
+goodix_milan_base_attempt_reset (GoodixMilanBaseAttempt *attempt)
+{
+ if (!attempt)
+ return;
+
+ goodix_milan_base_attempt_release_frames (attempt);
+ attempt->stage = GOODIX_MILAN_BASE_STAGE_IDLE;
+ attempt->mad = 0;
+ attempt->admission_status = 0;
+}
+
+void
+goodix_milan_base_attempt_cancel (GoodixMilanBaseAttempt *attempt)
+{
+ if (!attempt)
+ return;
+
+ goodix_milan_base_attempt_release_frames (attempt);
+ attempt->stage = GOODIX_MILAN_BASE_STAGE_CANCELLED;
+ attempt->mad = 0;
+ attempt->admission_status = 0;
+}
+
+void
+goodix_milan_base_attempt_take_frame (GoodixMilanBaseAttempt *attempt,
+ gboolean tx_on,
+ guint16 **frame,
+ gsize values)
+{
+ guint16 **slot;
+ gsize *slot_values;
+
+ g_return_if_fail (attempt != NULL);
+ g_return_if_fail (frame != NULL);
+
+ slot = tx_on ? &attempt->tx_on : &attempt->tx_off;
+ slot_values = tx_on ? &attempt->tx_on_values : &attempt->tx_off_values;
+ g_clear_pointer (slot, g_free);
+ *slot = g_steal_pointer (frame);
+ *slot_values = values;
+}
+
+gboolean
+goodix_milan_base_attempt_admit (GoodixMilanBaseAttempt *attempt,
+ GError **error)
+{
+ g_return_val_if_fail (attempt != NULL, FALSE);
+
+ attempt->stage = GOODIX_MILAN_BASE_STAGE_ADMIT_PAIR;
+ attempt->admission_status = 0;
+ if (!goodix_milan_base_pair_mad (attempt->tx_on, attempt->tx_on_values,
+ attempt->tx_off, attempt->tx_off_values,
+ &attempt->mad, error))
+ {
+ goodix_milan_base_attempt_release_frames (attempt);
+ return FALSE;
+ }
+
+ if (attempt->mad >= GOODIX_MILAN_BASE_MAD_LIMIT)
+ {
+ goodix_milan_base_attempt_release_frames (attempt);
+ attempt->stage = GOODIX_MILAN_BASE_STAGE_REJECTED;
+ return FALSE;
+ }
+
+ attempt->admitted = TRUE;
+ return TRUE;
+}
+
+gboolean
+goodix_milan_generation_allocate_id (guint64 *last_generation_id,
+ guint64 *generation_id,
+ GError **error)
+{
+ g_return_val_if_fail (last_generation_id != NULL, FALSE);
+ g_return_val_if_fail (generation_id != NULL, FALSE);
+
+ if (*last_generation_id == G_MAXUINT64)
+ {
+ g_set_error_literal (error, GOODIX_MILAN_BASE_ERROR,
+ GOODIX_MILAN_BASE_ERROR_ID_EXHAUSTED,
+ "Milan generation IDs are exhausted");
+ return FALSE;
+ }
+
+ *generation_id = ++(*last_generation_id);
+ return TRUE;
+}
+
+void
+goodix_milan_generation_reset_preprocess (GoodixMilanGeneration *generation)
+{
+ g_return_if_fail (generation != NULL);
+ goodix_milan_preprocess_reset (&generation->state);
+ memset (&generation->profile_state, 0, sizeof (generation->profile_state));
+}
+
+static void
+goodix_milan_generation_transfer_process_state (
+ GoodixMilanGeneration *destination,
+ const GoodixMilanGeneration *source)
+{
+ destination->state.stable_count = source->state.stable_count;
+ destination->state.auxiliary_sample_count =
+ source->state.auxiliary_sample_count;
+ destination->state.application_gain_initialized =
+ source->state.application_gain_initialized;
+ memcpy (destination->state.coarse_reference, source->state.coarse_reference,
+ sizeof (destination->state.coarse_reference));
+ memcpy (destination->state.auxiliary_gain_map,
+ source->state.auxiliary_gain_map,
+ sizeof (destination->state.auxiliary_gain_map));
+ memcpy (destination->state.secondary_auxiliary_gain_map,
+ source->state.secondary_auxiliary_gain_map,
+ sizeof (destination->state.secondary_auxiliary_gain_map));
+ memcpy (destination->state.application_gain_map,
+ source->state.application_gain_map,
+ sizeof (destination->state.application_gain_map));
+ /* Setup reloads the packet, but an entered native classifier imports it only
+ * once per process lifetime. Keep the loaded snapshot separate from globals. */
+ if (source->state.profile9_classifier_initialized)
+ {
+ destination->state.profile9_history_count =
+ source->state.profile9_history_count;
+ destination->state.profile9_history_update_count =
+ source->state.profile9_history_update_count;
+ destination->state.profile9_history_mask_threshold =
+ source->state.profile9_history_mask_threshold;
+ destination->state.profile9_history_mask_average =
+ source->state.profile9_history_mask_average;
+ memcpy (destination->state.profile9_history_reference,
+ source->state.profile9_history_reference,
+ sizeof (destination->state.profile9_history_reference));
+ memcpy (destination->state.profile9_reference_age,
+ source->state.profile9_reference_age,
+ sizeof (destination->state.profile9_reference_age));
+ memcpy (destination->state.profile9_component_age,
+ source->state.profile9_component_age,
+ sizeof (destination->state.profile9_component_age));
+ destination->state.extraction_classification =
+ source->state.extraction_classification;
+ destination->state.profile9_classifier_initialized = 1;
+ }
+ destination->profile_state = source->profile_state;
+ destination->profile_state.setup_refresh_pending = 1;
+ destination->profile_state.setup_not_ready = 0;
+ destination->process_state_retained = TRUE;
+}
+
+gboolean
+goodix_milan_base_attempt_publish (GoodixMilanBaseAttempt *attempt,
+ guint64 generation_id,
+ GoodixMilanGeneration **generation,
+ GError **error)
+{
+ GoodixMilanGeneration *published;
+
+ g_return_val_if_fail (attempt != NULL, FALSE);
+ g_return_val_if_fail (generation != NULL, FALSE);
+ if (!attempt->admitted || !attempt->tx_on || !attempt->tx_off ||
+ attempt->tx_on_values != GOODIX_MILAN_SENSOR_PIXELS ||
+ attempt->tx_off_values != GOODIX_MILAN_SENSOR_PIXELS ||
+ generation_id == 0)
+ {
+ g_set_error_literal (error, GOODIX_MILAN_BASE_ERROR,
+ GOODIX_MILAN_BASE_ERROR_INCOMPLETE,
+ "Cannot publish an incomplete Milan base generation");
+ goodix_milan_base_attempt_release_frames (attempt);
+ return FALSE;
+ }
+
+ published = g_new0 (GoodixMilanGeneration, 1);
+ published->generation_id = generation_id;
+ published->setup_tx_on = g_steal_pointer (&attempt->tx_on);
+ published->admitted = TRUE;
+ goodix_milan_generation_reset_preprocess (published);
+
+ g_clear_pointer (&attempt->tx_off, g_free);
+ attempt->tx_on_values = 0;
+ attempt->tx_off_values = 0;
+ attempt->admitted = FALSE;
+ attempt->stage = GOODIX_MILAN_BASE_STAGE_PUBLISH;
+ *generation = published;
+ return TRUE;
+}
+
+void
+goodix_milan_generation_free (GoodixMilanGeneration *generation)
+{
+ if (!generation)
+ return;
+
+ g_clear_pointer (&generation->setup_tx_on, g_free);
+ g_clear_pointer (&generation->setup_save, goodix_milan_setup_save_free);
+ memset (&generation->state, 0, sizeof (generation->state));
+ memset (&generation->profile_state, 0, sizeof (generation->profile_state));
+ g_free (generation);
+}
+
+void
+goodix_milan_generation_invalidate (GoodixMilanGeneration **generation)
+{
+ if (!generation || !*generation)
+ return;
+
+ goodix_milan_generation_free (g_steal_pointer (generation));
+}
+
+guint64
+goodix_milan_generation_note_use (GoodixMilanGeneration *generation)
+{
+ g_return_val_if_fail (generation != NULL, 0);
+ g_return_val_if_fail (generation->admitted, 0);
+
+ if (generation->use_count < G_MAXUINT64)
+ generation->use_count++;
+ return generation->use_count;
+}
+
+void
+goodix_milan_generation_note_identify_prelude (GoodixMilanGeneration *generation)
+{
+ g_return_if_fail (generation != NULL);
+ generation->identify_prelude_seen = TRUE;
+ if (generation->identify_prelude_count < G_MAXUINT)
+ generation->identify_prelude_count++;
+}
+
+gboolean
+goodix_milan_replace_raw_frame (guint16 **owner,
+ guint16 **frame,
+ gsize values,
+ GError **error)
+{
+ g_return_val_if_fail (owner != NULL, FALSE);
+ g_return_val_if_fail (frame != NULL, FALSE);
+
+ if (!*frame || values != GOODIX_MILAN_SENSOR_PIXELS)
+ {
+ g_set_error_literal (error, GOODIX_MILAN_BASE_ERROR,
+ GOODIX_MILAN_BASE_ERROR_INVALID_FRAME,
+ "Live Milan raw frame must contain exactly 9504 values");
+ g_clear_pointer (frame, g_free);
+ return FALSE;
+ }
+
+ g_clear_pointer (owner, g_free);
+ *owner = g_steal_pointer (frame);
+ return TRUE;
+}
+
+/* Preserve release source locations after removing the compile seam. */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/calibration.h"
+#include "device/commands.h"
+#include "device/image.h"
+#include "device/persistence.h"
+#include "device/transport.h"
+
+void
+goodix_milan_generation_retain_process (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (!self->milan_generation)
+ return;
+ /* Native detach clears setup/workspace, not algorithm process globals. Keep
+ * their source owner until the next base publication; never reuse its frame. */
+ goodix_milan_generation_invalidate (&self->milan_retained_generation);
+ self->milan_retained_generation = g_steal_pointer (&self->milan_generation);
+ g_clear_pointer (&self->milan_retained_generation->setup_save,
+ goodix_milan_setup_save_free);
+ g_clear_pointer (&self->milan_retained_generation->setup_tx_on, g_free);
+ self->milan_retained_generation->profile_state.setup_initialized = 0;
+ self->milan_retained_generation->profile_state.setup_refresh_pending = 0;
+ self->milan_retained_generation->profile_state.setup_not_ready = 0;
+}
+
+void
+goodix_milan_generation_prepare_setup (FpDevice *dev,
+ GoodixMilanGeneration *generation)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ g_autofree GoodixMilanGeneration *restored = NULL;
+
+ g_return_if_fail (generation != NULL);
+ if (generation->profile_state.setup_initialized &&
+ !generation->profile_state.setup_refresh_pending &&
+ !self->hardware_refresh_pending)
+ return;
+
+ /* Hardware publication is not engine consumption. Select the newest base
+ * only at sample delivery, while the coordinator excludes refresh/CPU work.
+ * The native callback consumes its marker even if the engine later fails. */
+ if (self->hardware_reference)
+ {
+ guint16 *setup = g_memdup2 (self->hardware_reference,
+ GOODIX_SENSOR_PIXELS * sizeof (guint16));
+
+ g_free (generation->setup_tx_on);
+ generation->setup_tx_on = setup;
+ /* Debug replay counts delivered samples within this reference, not
+ * across the lifetime of the retained preprocessing state. */
+ if (generation->generation_id != self->hardware_reference_id)
+ generation->use_count = 0;
+ generation->generation_id = self->hardware_reference_id;
+ }
+ if (self->hardware_refresh_pending)
+ generation->profile_state.setup_refresh_pending = 1;
+ self->hardware_refresh_pending = FALSE;
+
+ /* Select disk workspace at sample delivery, retaining process-owned state
+ * across a refresh. Setup admission and its flags remain runtime-owned. */
+ restored = g_new0 (GoodixMilanGeneration, 1);
+ goodix_milan_generation_reset_preprocess (restored);
+ g_clear_pointer (&generation->setup_save, goodix_milan_setup_save_free);
+ generation->setup_save = goodix_milan_persistence_restore (dev, restored);
+ if (generation->profile_state.setup_initialized ||
+ generation->process_state_retained)
+ goodix_milan_generation_transfer_process_state (restored, generation);
+ generation->state = restored->state;
+}
+
+typedef enum {
+ GOODIX_BASE_UPLOAD_CONFIG = 0,
+ GOODIX_BASE_UPLOAD_CONFIG_DONE,
+ GOODIX_BASE_EC_POWER_ON,
+ GOODIX_BASE_EC_POWER_ON_DONE,
+ GOODIX_BASE_FDT_TX_ON_BEFORE,
+ GOODIX_BASE_FDT_TX_ON_BEFORE_DONE,
+ GOODIX_BASE_CAPTURE_TX_ON,
+ GOODIX_BASE_CAPTURE_TX_ON_DONE,
+ GOODIX_BASE_FDT_TX_OFF,
+ GOODIX_BASE_FDT_TX_OFF_DONE,
+ GOODIX_BASE_VALIDATE_FDT_PAIR,
+ GOODIX_BASE_CAPTURE_TX_OFF,
+ GOODIX_BASE_CAPTURE_TX_OFF_DONE,
+ GOODIX_BASE_FDT_TX_ON_AFTER,
+ GOODIX_BASE_FDT_TX_ON_AFTER_DONE,
+ GOODIX_BASE_CLEANUP_SLEEP,
+ GOODIX_BASE_CLEANUP_EC_POWER_OFF,
+ GOODIX_BASE_CLEANUP_EC_POWER_OFF_DONE,
+ GOODIX_BASE_NUM_STATES,
+} GoodixBaseSsmState;
+
+typedef struct
+{
+ GoodixMilanBaseAttempt attempt;
+ FpiSsm *parent_ssm;
+ guint8 fdt_tx_on_before[GOODIX_FDT_BASE_LEN];
+ guint8 fdt_tx_off[GOODIX_FDT_BASE_LEN];
+ guint8 candidate_base_down[GOODIX_FDT_BASE_LEN];
+ guint8 candidate_base_up[GOODIX_FDT_BASE_LEN];
+ guint8 candidate_base_manual[GOODIX_FDT_BASE_LEN];
+ gboolean forced_refresh;
+ gboolean manage_ec_power;
+ gboolean leave_powered;
+ gboolean first_fdt_ready;
+ GoodixHealthMeasurement health_measurement;
+} GoodixBaseSsmData;
+
+static void
+goodix_base_ssm_data_free (GoodixBaseSsmData *data)
+{
+ if (!data)
+ return;
+ goodix_milan_base_attempt_reset (&data->attempt);
+ g_free (data);
+}
+
+static gboolean
+goodix_base_check_cancelled (FpiSsm *ssm,
+ FpiDeviceGoodix53x5 *self,
+ GoodixBaseSsmData *data)
+{
+ /* A dispatched FDT handler is synchronous in the native event worker.
+ * Finish its forced refresh before the coordinator honors action stop. */
+ if (data->forced_refresh)
+ return FALSE;
+
+ if (!self->cancel || !g_cancellable_is_cancelled (self->cancel))
+ return FALSE;
+
+ goodix_milan_base_attempt_cancel (&data->attempt);
+ fpi_ssm_mark_failed (ssm,
+ g_error_new_literal (G_IO_ERROR, G_IO_ERROR_CANCELLED,
+ "Milan base acquisition cancelled"));
+ return TRUE;
+}
+
+static guint16 *
+goodix_base_decode_reply (FpDevice *dev,
+ const gchar *role,
+ GError **error)
+{
+ guint16 *frame = goodix_cmd_dup_image_reply (dev, error);
+
+ if (!frame)
+ g_prefix_error (error, "%s: ", role);
+ return frame;
+}
+
+static gboolean
+goodix_base_parse_fdt (FpDevice *dev,
+ guint8 fdt_base[GOODIX_FDT_BASE_LEN],
+ guint16 *touch_flag,
+ GError **error)
+{
+ const guint8 *payload;
+ gsize payload_len;
+
+ if (!goodix_cmd_parse_fdt_manual_reply (dev, &payload, &payload_len, error))
+ return FALSE;
+ if (touch_flag)
+ *touch_flag = payload[2] | ((guint16) payload[3] << 8);
+ memcpy (fdt_base, payload + 4, GOODIX_FDT_BASE_LEN);
+ return TRUE;
+}
+
+#ifdef GOODIX53X5_DEBUG
+static void goodix_base_timing_start (FpiDeviceGoodix53x5 *self);
+static void goodix_base_timing_done (FpiDeviceGoodix53x5 *self,
+ FpDevice *dev,
+ const gchar *event);
+#else
+#define goodix_base_timing_start(...) G_STMT_START { } G_STMT_END
+#define goodix_base_timing_done(...) G_STMT_START { } G_STMT_END
+#endif
+
+static void
+goodix_base_complete_recovery (FpiSsm *ssm,
+ FpDevice *dev,
+ GoodixBaseSsmData *data,
+ const guint8 fdt_tx_on[GOODIX_FDT_BASE_LEN],
+ guint16 touch_flag,
+ const gchar *checkpoint)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ goodix_milan_base_attempt_reset (&data->attempt);
+ self->profile9_fdt.base_valid = FALSE;
+ goodix_device_generate_fdt_base (data->fdt_tx_on_before,
+ GOODIX_FDT_BASE_LEN,
+ self->profile9_fdt.base_down);
+ memcpy (self->profile9_fdt.base_up, self->profile9_fdt.base_down,
+ sizeof (self->profile9_fdt.base_up));
+ memcpy (self->profile9_fdt.base_manual, self->profile9_fdt.base_down,
+ sizeof (self->profile9_fdt.base_manual));
+
+ if (data->forced_refresh)
+ {
+ self->profile9_fdt.refresh_outcome =
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_VALIDATION_FAILED;
+ data->leave_powered = TRUE;
+ fp_info ("Profile-9 FDT refresh validation failed at %s", checkpoint);
+ goodix_base_timing_done (self, dev, "validation_failed");
+ fpi_ssm_mark_completed (ssm);
+ return;
+ }
+
+ goodix_milan_generation_retain_process (dev);
+ memset (&self->profile9_fdt.event, 0, sizeof (self->profile9_fdt.event));
+ if (fdt_tx_on)
+ {
+ self->profile9_fdt.event.touch_flag = touch_flag;
+ memcpy (self->profile9_fdt.event.raw, fdt_tx_on, GOODIX_FDT_BASE_LEN);
+ self->profile9_fdt.event.pending = TRUE;
+ }
+ /* Rejection admits recovery without manufacturing a sensor event. */
+ self->profile9_fdt.initial_recovery_pending = TRUE;
+ data->leave_powered = FALSE;
+
+ fp_info ("Milan base acquisition validation failed at %s (touch_flag=0x%03x)",
+ checkpoint, touch_flag & 0x0fff);
+ goodix_base_timing_done (self, dev, "validation_failed");
+ fpi_ssm_mark_completed (ssm);
+}
+
+#ifdef GOODIX53X5_DEBUG
+static void
+goodix_base_timing_start (FpiDeviceGoodix53x5 *self)
+{
+ self->debug_timing.ref_capture_started_us = g_get_monotonic_time ();
+ self->debug_timing.ref_capture_phase_started_us =
+ self->debug_timing.ref_capture_started_us;
+}
+
+static void
+goodix_base_timing_done (FpiDeviceGoodix53x5 *self,
+ FpDevice *dev,
+ const gchar *event)
+{
+ const gint64 now_us = g_get_monotonic_time ();
+
+ if (self->debug_timing.ref_capture_phase_started_us != 0)
+ {
+ goodix_debug_timing_log (
+ dev, "ref_capture", event,
+ now_us - self->debug_timing.ref_capture_phase_started_us,
+ NULL);
+ }
+ if (self->debug_timing.ref_capture_started_us != 0)
+ goodix_debug_timing_log (dev, "ref_capture", "total",
+ now_us - self->debug_timing.ref_capture_started_us,
+ NULL);
+ self->debug_timing.ref_capture_started_us = 0;
+ self->debug_timing.ref_capture_phase_started_us = 0;
+}
+#endif
+
+/* Native update_allbase exits early before its first manual sample, and runs
+ * the first-TX-on FDT postlude on every later ordinary acquisition failure.
+ * This result is not permission to destroy the retained image or marker. */
+static void
+goodix_base_command_result (FpiSsm *ssm, FpDevice *dev, guint8 status,
+ gboolean native_zero, GError *error)
+{
+ GoodixBaseSsmData *data = fpi_ssm_get_data (ssm);
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (!error)
+ {
+ fpi_ssm_next_state (ssm);
+ return;
+ }
+ if (!native_zero)
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+ fp_dbg ("Reference acquisition returned ordinary failure: %s", error->message);
+ g_clear_error (&error);
+ if (data->first_fdt_ready)
+ {
+ goodix_base_complete_recovery (ssm, dev, data, NULL, 0, "acquisition");
+ }
+ else
+ {
+ if (data->forced_refresh)
+ self->profile9_fdt.refresh_outcome =
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_VALIDATION_FAILED;
+ else
+ self->profile9_fdt.initial_recovery_pending = TRUE;
+ fpi_ssm_mark_completed (ssm);
+ }
+}
+
+static void
+goodix_base_health_done (FpDevice *dev,
+ const GoodixHealthMeasurement *measurement,
+ GError *error, gpointer user_data)
+{
+ FpiSsm *ssm = user_data;
+ GoodixBaseSsmData *data = fpi_ssm_get_data (ssm);
+
+ if (error)
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ }
+ else
+ {
+ /* The pair owns its frames and lends only these two measurement scalars. */
+ data->health_measurement = *measurement;
+ fpi_ssm_next_state (ssm);
+ }
+}
+
+static void
+goodix_base_ssm_handler (FpiSsm *ssm,
+ FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixBaseSsmData *data = fpi_ssm_get_data (ssm);
+
+ g_autoptr(GError) error = NULL;
+
+ if (fpi_ssm_get_cur_state (ssm) < GOODIX_BASE_CLEANUP_SLEEP &&
+ goodix_base_check_cancelled (ssm, self, data))
+ return;
+
+ switch (fpi_ssm_get_cur_state (ssm))
+ {
+ case GOODIX_BASE_UPLOAD_CONFIG:
+ if (!data->forced_refresh)
+ {
+ goodix_base_timing_start (self);
+ fpi_ssm_jump_to_state (ssm, data->manage_ec_power ?
+ GOODIX_BASE_EC_POWER_ON :
+ GOODIX_BASE_FDT_TX_ON_BEFORE);
+ return;
+ }
+ else
+ {
+ goodix_cmd_restore_config (ssm, dev, goodix_base_command_result);
+ }
+ break;
+
+ case GOODIX_BASE_UPLOAD_CONFIG_DONE:
+ goodix_base_timing_start (self);
+ fpi_ssm_jump_to_state (ssm, data->manage_ec_power ?
+ GOODIX_BASE_EC_POWER_ON :
+ GOODIX_BASE_FDT_TX_ON_BEFORE);
+ break;
+
+ case GOODIX_BASE_EC_POWER_ON:
+ goodix_cmd_ec_control (ssm, dev, TRUE);
+ break;
+
+ case GOODIX_BASE_EC_POWER_ON_DONE:
+ goodix_debug_timing_log (dev, "ref_capture", "ec_power_on",
+ g_get_monotonic_time () -
+ self->debug_timing.ref_capture_phase_started_us,
+ NULL);
+ GOODIX53X5_DEBUG_ONLY (
+ self->debug_timing.ref_capture_phase_started_us =
+ g_get_monotonic_time ();
+ )
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_BASE_FDT_TX_ON_BEFORE:
+ data->attempt.stage = GOODIX_MILAN_BASE_STAGE_FDT_TX_ON_BEFORE;
+ goodix_cmd_fdt_manual_result (ssm, dev, TRUE,
+ self->profile9_fdt.base_manual,
+ goodix_base_command_result);
+ break;
+
+ case GOODIX_BASE_FDT_TX_ON_BEFORE_DONE:
+ if (!goodix_base_parse_fdt (dev, data->fdt_tx_on_before, NULL, &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ data->first_fdt_ready = TRUE;
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_BASE_CAPTURE_TX_ON:
+ data->attempt.stage = GOODIX_MILAN_BASE_STAGE_CAPTURE_TX_ON;
+ goodix_cmd_request_image_result (ssm, dev, TRUE, TRUE, FALSE,
+ self->calib.dac_l, goodix_base_command_result);
+ break;
+
+ case GOODIX_BASE_CAPTURE_TX_ON_DONE:
+ {
+ g_autofree guint16 *frame =
+ goodix_base_decode_reply (dev, "TX-on base", &error);
+
+ if (!frame)
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ goodix_milan_base_attempt_take_frame (&data->attempt, TRUE, &frame,
+ GOODIX_SENSOR_PIXELS);
+ fpi_ssm_next_state (ssm);
+ }
+ break;
+
+ case GOODIX_BASE_FDT_TX_OFF:
+ data->attempt.stage = GOODIX_MILAN_BASE_STAGE_FDT_TX_OFF;
+ goodix_cmd_fdt_manual_result (ssm, dev, FALSE,
+ self->profile9_fdt.base_manual,
+ goodix_base_command_result);
+ break;
+
+ case GOODIX_BASE_FDT_TX_OFF_DONE:
+ if (!goodix_base_parse_fdt (dev, data->fdt_tx_off, NULL, &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ goodix_health_start_pair (dev, GOODIX_HEALTH_PAIR_BASE,
+ goodix_base_health_done, ssm);
+ break;
+
+ case GOODIX_BASE_VALIDATE_FDT_PAIR:
+ if (!goodix_device_is_fdt_base_valid (data->fdt_tx_on_before,
+ data->fdt_tx_off,
+ GOODIX_FDT_BASE_LEN,
+ self->calib.delta_fdt))
+ {
+ goodix_base_complete_recovery (
+ ssm, dev, data, NULL, 0, "fdt-tx-on/tx-off");
+ return;
+ }
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_BASE_CAPTURE_TX_OFF:
+ data->attempt.stage = GOODIX_MILAN_BASE_STAGE_CAPTURE_TX_OFF;
+ goodix_cmd_request_image_result (ssm, dev, FALSE, TRUE, FALSE,
+ self->calib.dac_l, goodix_base_command_result);
+ break;
+
+ case GOODIX_BASE_CAPTURE_TX_OFF_DONE:
+ {
+ g_autofree guint16 *frame =
+ goodix_base_decode_reply (dev, "TX-off base", &error);
+
+ if (!frame)
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ goodix_milan_base_attempt_take_frame (&data->attempt, FALSE, &frame,
+ GOODIX_SENSOR_PIXELS);
+
+ goodix_debug_dump_raw12 ("raw12-ref-txon", data->attempt.tx_on,
+ GOODIX_SENSOR_PIXELS);
+ goodix_debug_dump_raw12 ("raw12-ref", data->attempt.tx_off,
+ GOODIX_SENSOR_PIXELS);
+
+ if (!goodix_milan_base_attempt_admit (&data->attempt, &error))
+ {
+ if (error)
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ else
+ goodix_base_complete_recovery (
+ ssm, dev, data, NULL, 0, "tx-on/tx-off");
+ return;
+ }
+ fpi_ssm_next_state (ssm);
+ }
+ break;
+
+ case GOODIX_BASE_FDT_TX_ON_AFTER:
+ data->attempt.stage = GOODIX_MILAN_BASE_STAGE_FDT_TX_ON_AFTER;
+ goodix_cmd_fdt_manual_result (ssm, dev, TRUE,
+ self->profile9_fdt.base_manual,
+ goodix_base_command_result);
+ break;
+
+ case GOODIX_BASE_FDT_TX_ON_AFTER_DONE:
+ {
+ guint8 fdt_tx_on_after[GOODIX_FDT_BASE_LEN];
+ guint64 generation_id;
+ GoodixMilanGeneration *generation = NULL;
+ g_autofree guint16 *hardware_reference = NULL;
+ guint16 touch_flag;
+
+ if (!goodix_base_parse_fdt (dev, fdt_tx_on_after, &touch_flag, &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ if (!goodix_device_is_fdt_base_valid (fdt_tx_on_after,
+ data->fdt_tx_off,
+ GOODIX_FDT_BASE_LEN,
+ self->calib.delta_fdt))
+ {
+ goodix_base_complete_recovery (
+ ssm, dev, data, fdt_tx_on_after, touch_flag, "tx-on-after");
+ return;
+ }
+
+ /* HAL+0x248 follows every admitted hardware base, even when the engine
+ * keeps an older consumed setup after unmarked checkbase recovery. */
+ hardware_reference = g_memdup2 (data->attempt.tx_on,
+ GOODIX_SENSOR_PIXELS * sizeof (guint16));
+ if (!goodix_milan_generation_allocate_id (&self->last_milan_generation_id,
+ &generation_id, &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+
+ /* Native update_allbase derives every FDT base from this first
+ * TX-on sample after the complete sequence is admitted. */
+ goodix_device_generate_fdt_base (data->fdt_tx_on_before,
+ GOODIX_FDT_BASE_LEN,
+ data->candidate_base_down);
+ memcpy (data->candidate_base_up, data->candidate_base_down,
+ GOODIX_FDT_BASE_LEN);
+ memcpy (data->candidate_base_manual, data->candidate_base_down,
+ GOODIX_FDT_BASE_LEN);
+ data->attempt.stage = GOODIX_MILAN_BASE_STAGE_PUBLISH;
+ if (data->forced_refresh && self->milan_generation)
+ {
+ /* Keep the engine-consumed reference/workspace until delivery. */
+ goodix_milan_base_attempt_release_frames (&data->attempt);
+ }
+ else
+ {
+ if (!goodix_milan_base_attempt_publish (&data->attempt, generation_id,
+ &generation,
+ &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+
+ if (self->milan_retained_generation)
+ goodix_milan_generation_transfer_process_state (
+ generation, self->milan_retained_generation);
+ goodix_milan_generation_invalidate (&self->milan_generation);
+ goodix_milan_generation_invalidate (&self->milan_retained_generation);
+ self->milan_generation = generation;
+ }
+ /* Preparation above may fail; publish the admitted tuple only after
+ * all owned replacements and the identity have been prepared. */
+ g_clear_pointer (&self->hardware_reference, g_free);
+ self->hardware_reference = g_steal_pointer (&hardware_reference);
+ self->hardware_reference_id = generation_id;
+ if (data->forced_refresh &&
+ self->profile9_fdt.refresh_reason != GOODIX_PROFILE9_FDT_REFRESH_INVALID_BASE &&
+ self->profile9_fdt.refresh_reason != GOODIX_PROFILE9_FDT_REFRESH_UP_INVALID_BASE)
+ self->hardware_refresh_pending = TRUE;
+ memcpy (self->profile9_fdt.base_down, data->candidate_base_down,
+ GOODIX_FDT_BASE_LEN);
+ memcpy (self->profile9_fdt.base_up, data->candidate_base_up,
+ GOODIX_FDT_BASE_LEN);
+ memcpy (self->profile9_fdt.base_manual, data->candidate_base_manual,
+ GOODIX_FDT_BASE_LEN);
+ /* Native false-down and up/checkbase callers retain the anchor. */
+ if (!data->forced_refresh ||
+ (self->profile9_fdt.refresh_reason != GOODIX_PROFILE9_FDT_REFRESH_FALSE_DOWN &&
+ self->profile9_fdt.refresh_reason != GOODIX_PROFILE9_FDT_REFRESH_UP_INVALID_BASE))
+ {
+ memset (self->profile9_fdt.drift_anchor, 0,
+ sizeof (self->profile9_fdt.drift_anchor));
+ self->profile9_fdt.drift_anchor_empty = TRUE;
+ }
+ self->profile9_fdt.base_valid = TRUE;
+ goodix_health_seed_base (&self->health, &data->health_measurement);
+ self->profile9_fdt.event.pending = FALSE;
+ self->profile9_fdt.initial_recovery_pending = FALSE;
+ if (data->forced_refresh)
+ self->profile9_fdt.refresh_outcome =
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_PUBLISHED;
+ GOODIX53X5_DEBUG_ONLY (
+ fp_info ("Admitted Milan generation id=%" G_GUINT64_FORMAT
+ " subtype=%u MAD=%" G_GUINT64_FORMAT,
+ generation_id, self->milan_sensor_subtype,
+ data->attempt.mad);
+ )
+ data->leave_powered = TRUE;
+ goodix_base_timing_done (self, dev, "base_generation");
+ fpi_ssm_mark_completed (ssm);
+ }
+ break;
+
+ case GOODIX_BASE_CLEANUP_SLEEP:
+ /* Cold initialization owns a common firmware-query/sleep tail, even
+ * when allbase exits before its first manual sample or rejects a pair.
+ * Do not insert a child power transition before that tail. */
+ if (data->leave_powered ||
+ (!data->forced_refresh && !data->manage_ec_power && !fpi_ssm_get_error (ssm)))
+ fpi_ssm_jump_to_state (ssm, GOODIX_BASE_NUM_STATES);
+ else
+ goodix_cmd_set_sleep_mode (ssm, dev);
+ break;
+
+ case GOODIX_BASE_CLEANUP_EC_POWER_OFF:
+ /* Keep shutdown best-effort after failures even when the nominal native
+ * acquisition path does not own EC power transitions. */
+ if (data->manage_ec_power || fpi_ssm_get_error (ssm))
+ goodix_cmd_ec_control (ssm, dev, FALSE);
+ else
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_BASE_CLEANUP_EC_POWER_OFF_DONE:
+ goodix_base_timing_done (self, dev, "cleanup");
+ fpi_ssm_mark_completed (ssm);
+ break;
+
+ case GOODIX_BASE_NUM_STATES:
+ g_assert_not_reached ();
+ }
+}
+
+static void
+goodix_base_ssm_done (FpiSsm *ssm,
+ FpDevice *dev,
+ GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixBaseSsmData *data = fpi_ssm_get_data (ssm);
+
+ if (data->forced_refresh && error)
+ {
+ if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
+ {
+ self->profile9_fdt.refresh_outcome =
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_CANCELLED;
+ }
+ else
+ {
+ self->profile9_fdt.refresh_outcome =
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_FATAL;
+ self->needs_reinit = TRUE;
+ }
+ }
+
+ if (error)
+ fpi_ssm_mark_failed (data->parent_ssm, error);
+ else
+ fpi_ssm_next_state (data->parent_ssm);
+}
+
+static void
+goodix_milan_base_start_subsm (FpiSsm *parent_ssm,
+ FpDevice *dev,
+ gboolean forced_refresh,
+ gboolean manage_ec_power,
+ GoodixProfile9FdtRefreshReason reason)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixBaseSsmData *data;
+ FpiSsm *sub;
+
+ if (forced_refresh)
+ {
+ self->profile9_fdt.refresh_reason = reason;
+ self->profile9_fdt.refresh_outcome =
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_IN_PROGRESS;
+ self->profile9_fdt.base_valid = FALSE;
+ }
+
+ if (self->milan_sensor_subtype != GOODIX_MILAN_VALIDATED_SUBTYPE)
+ {
+ if (forced_refresh)
+ {
+ self->profile9_fdt.refresh_outcome =
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_FATAL;
+ self->needs_reinit = TRUE;
+ }
+ fpi_ssm_mark_failed (parent_ssm,
+ fpi_device_error_new_msg (FP_DEVICE_ERROR_NOT_SUPPORTED,
+ "Native Milan subtype invariant failed for chip 0x%08x subtype %u",
+ self->chip_id,
+ self->milan_sensor_subtype));
+ return;
+ }
+
+ if (!forced_refresh && self->milan_generation != NULL)
+ {
+ fpi_ssm_next_state (parent_ssm);
+ return;
+ }
+
+ if (!forced_refresh)
+ {
+ self->profile9_fdt.base_valid = FALSE;
+ self->profile9_fdt.initial_recovery_pending = FALSE;
+ }
+ data = g_new0 (GoodixBaseSsmData, 1);
+ data->parent_ssm = parent_ssm;
+ data->forced_refresh = forced_refresh;
+ data->manage_ec_power = manage_ec_power;
+ data->leave_powered = forced_refresh;
+ goodix_milan_base_attempt_init (&data->attempt);
+ sub = fpi_ssm_new_full (dev, goodix_base_ssm_handler,
+ GOODIX_BASE_NUM_STATES,
+ GOODIX_BASE_CLEANUP_SLEEP,
+ "goodix-milan-base");
+ fpi_ssm_set_data (sub, data, (GDestroyNotify) goodix_base_ssm_data_free);
+ fpi_ssm_start (sub, goodix_base_ssm_done);
+}
+
+void
+goodix_milan_base_start_ensure_subsm (FpiSsm *parent_ssm,
+ FpDevice *dev,
+ gboolean manage_ec_power)
+{
+ goodix_milan_base_start_subsm (parent_ssm, dev, FALSE, manage_ec_power,
+ GOODIX_PROFILE9_FDT_REFRESH_NONE);
+}
+
+void
+goodix_milan_base_start_forced_refresh_subsm (
+ FpiSsm *parent_ssm,
+ FpDevice *dev,
+ GoodixProfile9FdtRefreshReason reason)
+{
+ g_return_if_fail (reason != GOODIX_PROFILE9_FDT_REFRESH_NONE);
+ goodix_milan_base_start_subsm (parent_ssm, dev, TRUE, FALSE, reason);
+}
diff --git a/libfprint/drivers/goodix53x5/device/base.h b/libfprint/drivers/goodix53x5/device/base.h
new file mode 100644
index 0000000..7771696
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/base.h
@@ -0,0 +1,191 @@
+/*
+ * Goodix 53x5 driver for libfprint - native Milan base generation
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include <glib.h>
+
+#include "milan/milan.h"
+
+#define GOODIX_FDT_BASE_LEN 24
+#define GOODIX_PROFILE9_FDT_AREA_COUNT 12
+#define GOODIX_MILAN_PROFILE9_CHIP_FAMILY_MASK 0xffffff00u
+#define GOODIX_MILAN_PROFILE9_CHIP_FAMILY_PREFIX 0x00220c00u
+#define GOODIX_MILAN_VALIDATED_CHIP_ID 0x00220ca1u
+#define GOODIX_MILAN_VALIDATED_SUBTYPE 12
+#define GOODIX_MILAN_BASE_BORDER 2
+#define GOODIX_MILAN_BASE_MAD_LIMIT 200
+
+typedef struct _FpiSsm FpiSsm;
+typedef struct _FpDevice FpDevice;
+typedef struct _GoodixMilanSetupSave GoodixMilanSetupSave;
+
+typedef enum
+{
+ GOODIX_PROFILE9_FDT_WAIT_NONE = 0,
+ GOODIX_PROFILE9_FDT_WAIT_DOWN,
+ GOODIX_PROFILE9_FDT_WAIT_UP,
+} GoodixProfile9FdtWaitMode;
+
+typedef enum
+{
+ GOODIX_PROFILE9_FDT_LIFECYCLE_STOPPED = 0,
+ GOODIX_PROFILE9_FDT_LIFECYCLE_ACTIVE,
+ GOODIX_PROFILE9_FDT_LIFECYCLE_STOPPING,
+} GoodixProfile9FdtLifecycle;
+
+typedef enum
+{
+ GOODIX_PROFILE9_FDT_REFRESH_NONE = 0,
+ GOODIX_PROFILE9_FDT_REFRESH_FALSE_DOWN,
+ GOODIX_PROFILE9_FDT_REFRESH_REVERSE,
+ GOODIX_PROFILE9_FDT_REFRESH_UP,
+ GOODIX_PROFILE9_FDT_REFRESH_INVALID_BASE,
+ GOODIX_PROFILE9_FDT_REFRESH_UP_INVALID_BASE,
+} GoodixProfile9FdtRefreshReason;
+
+typedef enum
+{
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_NONE = 0,
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_IN_PROGRESS,
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_PUBLISHED,
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_VALIDATION_FAILED,
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_CANCELLED,
+ GOODIX_PROFILE9_FDT_REFRESH_OUTCOME_FATAL,
+} GoodixProfile9FdtRefreshOutcome;
+
+typedef struct
+{
+ guint16 irq;
+ guint16 touch_flag;
+ guint8 raw[GOODIX_FDT_BASE_LEN];
+ gboolean pending;
+} GoodixProfile9FdtEvent;
+
+typedef struct
+{
+ GoodixProfile9FdtWaitMode wait_mode;
+ GoodixProfile9FdtLifecycle lifecycle;
+ FpiSsm *owner;
+ gboolean base_valid;
+ guint16 drift_anchor[GOODIX_PROFILE9_FDT_AREA_COUNT];
+ gboolean drift_anchor_empty;
+ guint8 base_down[GOODIX_FDT_BASE_LEN];
+ guint8 base_up[GOODIX_FDT_BASE_LEN];
+ guint8 base_manual[GOODIX_FDT_BASE_LEN];
+ GoodixProfile9FdtEvent event;
+ gboolean initial_recovery_pending;
+ GoodixProfile9FdtRefreshReason refresh_reason;
+ GoodixProfile9FdtRefreshOutcome refresh_outcome;
+} GoodixProfile9FdtState;
+
+typedef enum
+{
+ GOODIX_MILAN_BASE_STAGE_IDLE = 0,
+ GOODIX_MILAN_BASE_STAGE_FDT_TX_ON_BEFORE,
+ GOODIX_MILAN_BASE_STAGE_CAPTURE_TX_ON,
+ GOODIX_MILAN_BASE_STAGE_FDT_TX_OFF,
+ GOODIX_MILAN_BASE_STAGE_CAPTURE_TX_OFF,
+ GOODIX_MILAN_BASE_STAGE_ADMIT_PAIR,
+ GOODIX_MILAN_BASE_STAGE_FDT_TX_ON_AFTER,
+ GOODIX_MILAN_BASE_STAGE_PUBLISH,
+ GOODIX_MILAN_BASE_STAGE_REJECTED,
+ GOODIX_MILAN_BASE_STAGE_CANCELLED,
+ GOODIX_MILAN_BASE_STAGE_COUNT,
+} GoodixMilanBaseStage;
+
+typedef struct
+{
+ GoodixMilanBaseStage stage;
+ guint16 *tx_on;
+ guint16 *tx_off;
+ gsize tx_on_values;
+ gsize tx_off_values;
+ guint64 mad;
+ gint32 admission_status;
+ gboolean admitted;
+} GoodixMilanBaseAttempt;
+
+typedef struct
+{
+ guint64 generation_id;
+ /* Reference consumed by preprocessing; unmarked hardware recovery retains it. */
+ guint16 *setup_tx_on;
+ GoodixMilanPreprocessState state;
+ GoodixMilanProfileState profile_state;
+ gboolean admitted;
+ gboolean identify_prelude_seen;
+ guint identify_prelude_count;
+ /* Debug sample delivery count for generation_id/setup_tx_on, independent
+ * of the preprocessing state retained when the hardware reference changes. */
+ guint64 use_count;
+ gboolean process_state_retained;
+ GoodixMilanSetupSave *setup_save;
+} GoodixMilanGeneration;
+
+typedef enum
+{
+ GOODIX_MILAN_BASE_ERROR_INVALID_FRAME,
+ GOODIX_MILAN_BASE_ERROR_INCOMPLETE,
+ GOODIX_MILAN_BASE_ERROR_ID_EXHAUSTED,
+} GoodixMilanBaseError;
+
+#define GOODIX_MILAN_BASE_ERROR (goodix_milan_base_error_quark ())
+GQuark goodix_milan_base_error_quark (void);
+
+gboolean goodix_milan_runtime_subtype_for_chip (guint32 chip_id,
+ guint16 *subtype);
+
+gboolean goodix_milan_base_pair_mad (const guint16 *tx_on,
+ gsize tx_on_values,
+ const guint16 *tx_off,
+ gsize tx_off_values,
+ guint64 *mad,
+ GError **error);
+
+void goodix_milan_base_attempt_init (GoodixMilanBaseAttempt *attempt);
+void goodix_milan_base_attempt_reset (GoodixMilanBaseAttempt *attempt);
+void goodix_milan_base_attempt_cancel (GoodixMilanBaseAttempt *attempt);
+void goodix_milan_base_attempt_take_frame (GoodixMilanBaseAttempt *attempt,
+ gboolean tx_on,
+ guint16 **frame,
+ gsize values);
+gboolean goodix_milan_base_attempt_admit (GoodixMilanBaseAttempt *attempt,
+ GError **error);
+
+gboolean goodix_milan_generation_allocate_id (guint64 *last_generation_id,
+ guint64 *generation_id,
+ GError **error);
+gboolean goodix_milan_base_attempt_publish (GoodixMilanBaseAttempt *attempt,
+ guint64 generation_id,
+ GoodixMilanGeneration **generation,
+ GError **error);
+
+void goodix_milan_generation_reset_preprocess (GoodixMilanGeneration *generation);
+void goodix_milan_generation_prepare_setup (FpDevice *dev,
+ GoodixMilanGeneration *generation);
+void goodix_milan_generation_free (GoodixMilanGeneration *generation);
+void goodix_milan_generation_invalidate (GoodixMilanGeneration **generation);
+void goodix_milan_generation_retain_process (FpDevice *dev);
+guint64 goodix_milan_generation_note_use (GoodixMilanGeneration *generation);
+void goodix_milan_generation_note_identify_prelude (GoodixMilanGeneration *generation);
+
+gboolean goodix_milan_replace_raw_frame (guint16 **owner,
+ guint16 **frame,
+ gsize values,
+ GError **error);
+
+void goodix_milan_base_start_ensure_subsm (FpiSsm *parent_ssm,
+ FpDevice *dev,
+ gboolean manage_ec_power);
+void goodix_milan_base_start_forced_refresh_subsm (
+ FpiSsm *parent_ssm,
+ FpDevice *dev,
+ GoodixProfile9FdtRefreshReason reason);
diff --git a/libfprint/drivers/goodix53x5/device/calibration.c b/libfprint/drivers/goodix53x5/device/calibration.c
new file mode 100644
index 0000000..cb8a62e
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/calibration.c
@@ -0,0 +1,579 @@
+/*
+ * Goodix 53x5 driver for libfprint — OTP, config, and FDT base math
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/calibration.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+/* usbinterface.dll 007c84/0115a4: the first pass includes the border; only the
+ * second pass selects interior pixels. Keep signed differences/group means
+ * separate from the unsigned selected sum and mean. */
+static gboolean
+goodix_dynamic_dac_mean (const guint16 *live,
+ const guint16 *reference,
+ guint16 reg,
+ guint32 *mean)
+{
+ guint32 high_sum = 0, low_sum = 0;
+ gint32 high_count = 0, low_count = 0;
+ guint32 selected_sum = 0, selected_count = 0, nonzero = 0;
+ const guint32 interior = (GOODIX_SENSOR_HEIGHT - 2) * (GOODIX_SENSOR_WIDTH - 2);
+ /* Native writes only the low word of a later dword mask input. Use zero for
+ * its unwritten upper word, retaining the defined register bias in both the
+ * positive counter and the no-high-group threshold. */
+ guint32 positive = reg;
+ gint32 threshold = reg;
+
+ for (guint i = 0; i < GOODIX_SENSOR_PIXELS; i++)
+ {
+ gint32 sample = (gint16) live[i];
+ gint32 base = (gint16) reference[i];
+ gint32 difference = base - sample;
+
+ if (difference > 3800)
+ {
+ high_sum += (guint32) difference;
+ high_count++;
+ }
+ else
+ {
+ low_sum += (guint32) difference;
+ low_count++;
+ }
+ positive += sample > base;
+ }
+
+ if (high_count)
+ {
+ gint32 high_mean = (gint32) high_sum / high_count;
+ gint32 low_mean = low_count ? (gint32) low_sum / low_count : 0;
+
+ threshold = 3800 - (high_mean - low_mean) / 4;
+ }
+
+ for (guint row = 1; row < GOODIX_SENSOR_HEIGHT - 1; row++)
+ for (guint column = 1; column < GOODIX_SENSOR_WIDTH - 1; column++)
+ {
+ guint i = row * GOODIX_SENSOR_WIDTH + column;
+ gint32 sample = (gint16) live[i];
+ gint32 base = (gint16) reference[i];
+
+ nonzero += sample != 0;
+ if (sample <= 3800 ||
+ (base - sample >= threshold && threshold != 0 &&
+ ((gint32) (positive * 10u) <= GOODIX_SENSOR_PIXELS || sample <= base)))
+ {
+ selected_sum += (guint32) sample;
+ selected_count++;
+ }
+ }
+
+ /* Native rounds the divisions to binary32 before the binary64 comparisons. */
+ if ((double) ((float) nonzero / (float) interior) > 0.95 &&
+ (double) ((float) selected_count / (float) interior) <= 0.4)
+ return FALSE;
+
+ *mean = selected_count ? selected_sum / selected_count : 0;
+ return TRUE;
+}
+
+static guint16
+goodix_dynamic_dac_step (guint16 reg,
+ guint16 default_dac,
+ guint16 tcode,
+ guint32 mean,
+ gboolean correction)
+{
+ gboolean upward = mean > 2000;
+ guint32 delta = upward ? mean - 2000u : 2000u - mean;
+ guint16 temperature = (guint16) ((tcode ? tcode : 128) << 4);
+ double scaled = ((double) (guint64) delta * 0.25) / ((double) temperature * 0.283);
+ /* CVTTSD2SI returns INT_MIN for an invalid conversion; its low word is zero.
+ * The verified OTP domain always supplies a nonzero denominator. */
+ guint16 step = scaled >= 0.0 && scaled < 2147483648.0 ? (guint16) (gint32) scaled : 0;
+ guint32 field = reg & 0x1ff0;
+ guint16 candidate;
+
+ if (step == 0)
+ step = 1;
+
+ if (upward)
+ {
+ guint32 ceiling = 16u * ((guint32) default_dac + 30u);
+
+ candidate = field + 16u * step > ceiling ? ceiling : reg + 16u * step;
+ }
+ else
+ {
+ /* Middle correction compares D-5+step, but still caps at D-4. This
+ * asymmetry can alternate around the floor; it is not a common clamp. */
+ gint32 floor_test = (gint32) (16u * ((guint32) default_dac -
+ (correction ? 5u : 4u) + step));
+
+ candidate = (gint32) field < floor_test ?
+ 16u * default_dac - 64u : reg - 16u * step;
+ }
+
+ return reg ^ ((candidate ^ reg) & 0x1ff0);
+}
+
+void
+goodix_device_adjust_dac (GoodixDynamicDacState *state,
+ GoodixCalibParams *params,
+ const guint16 *live,
+ const guint16 *reference)
+{
+ guint16 reg = (guint16) (params->dac_h << 4) | 8;
+ guint32 mean;
+ gboolean correction = FALSE;
+
+ if (!goodix_dynamic_dac_mean (live, reference, reg, &mean))
+ goto out;
+
+ if (mean > 3200 || mean < 1500)
+ {
+ guint16 *streak = mean > 3200 ? &state->high : &state->low;
+ guint16 *opposite = mean > 3200 ? &state->low : &state->high;
+ guint16 was_active = state->active;
+
+ if (*opposite < 3)
+ *opposite = 0;
+ else
+ was_active = state->active = 0;
+ if (*streak < 3)
+ (*streak)++;
+ if (*streak < 3)
+ goto out;
+ *opposite = 0;
+ if (was_active == 0)
+ {
+ state->active = 1;
+ state->adjustments = 0;
+ }
+ }
+ else if (state->active == 1)
+ {
+ if (mean >= 1900 && mean <= 2100)
+ {
+ state->active = state->high = state->low = 0;
+ goto out;
+ }
+ correction = TRUE;
+ }
+ else
+ {
+ if (state->high < 3)
+ state->high = 0;
+ if (state->low < 3)
+ state->low = 0;
+ goto out;
+ }
+
+ reg = goodix_dynamic_dac_step (reg, state->default_dac, params->tcode,
+ mean, correction);
+ state->adjustments = (guint16) (state->adjustments + 1);
+out:
+ /* Retain the native word here; algorithm consumers project its low byte. */
+ params->dac_h = reg >> 4;
+}
+
+/* OTP hash lookup table (from driver_53x5.py) */
+static const guint8 otp_hash_table[256] = {
+ 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15,
+ 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d,
+ 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65,
+ 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d,
+ 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5,
+ 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd,
+ 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85,
+ 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd,
+ 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2,
+ 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea,
+ 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2,
+ 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a,
+ 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32,
+ 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a,
+ 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42,
+ 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a,
+ 0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c,
+ 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4,
+ 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec,
+ 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4,
+ 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c,
+ 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44,
+ 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c,
+ 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34,
+ 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b,
+ 0x76, 0x71, 0x78, 0x7f, 0x6a, 0x6d, 0x64, 0x63,
+ 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b,
+ 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13,
+ 0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb,
+ 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8d, 0x84, 0x83,
+ 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb,
+ 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3,
+};
+
+/* Default configuration (from driver_53x5.py DEFAULT_CONFIG) */
+static const guint8 default_config[] = {
+ 0x40, 0x11, 0x6c, 0x7d, 0x28, 0xa5, 0x28, 0xcd,
+ 0x1c, 0xe9, 0x10, 0xf9, 0x00, 0xf9, 0x00, 0xf9,
+ 0x00, 0x04, 0x02, 0x00, 0x00, 0x08, 0x00, 0x11,
+ 0x11, 0xba, 0x00, 0x01, 0x80, 0xca, 0x00, 0x07,
+ 0x00, 0x84, 0x00, 0xbe, 0xb2, 0x86, 0x00, 0xc5,
+ 0xb9, 0x88, 0x00, 0xb5, 0xad, 0x8a, 0x00, 0x9d,
+ 0x95, 0x8c, 0x00, 0x00, 0xbe, 0x8e, 0x00, 0x00,
+ 0xc5, 0x90, 0x00, 0x00, 0xb5, 0x92, 0x00, 0x00,
+ 0x9d, 0x94, 0x00, 0x00, 0xaf, 0x96, 0x00, 0x00,
+ 0xbf, 0x98, 0x00, 0x00, 0xb6, 0x9a, 0x00, 0x00,
+ 0xa7, 0x30, 0x00, 0x6c, 0x1c, 0x50, 0x00, 0x01,
+ 0x05, 0xd0, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00,
+ 0x00, 0x72, 0x00, 0x78, 0x56, 0x74, 0x00, 0x34,
+ 0x12, 0x26, 0x00, 0x00, 0x12, 0x20, 0x00, 0x10,
+ 0x40, 0x12, 0x00, 0x03, 0x04, 0x02, 0x02, 0x16,
+ 0x21, 0x2c, 0x02, 0x0a, 0x03, 0x2a, 0x01, 0x02,
+ 0x00, 0x22, 0x00, 0x01, 0x20, 0x24, 0x00, 0x32,
+ 0x00, 0x80, 0x00, 0x05, 0x04, 0x5c, 0x00, 0x00,
+ 0x01, 0x56, 0x00, 0x28, 0x20, 0x58, 0x00, 0x01,
+ 0x00, 0x32, 0x00, 0x24, 0x02, 0x82, 0x00, 0x80,
+ 0x0c, 0x20, 0x02, 0x88, 0x0d, 0x2a, 0x01, 0x92,
+ 0x07, 0x22, 0x00, 0x01, 0x20, 0x24, 0x00, 0x14,
+ 0x00, 0x80, 0x00, 0x05, 0x04, 0x5c, 0x00, 0x00,
+ 0x01, 0x56, 0x00, 0x08, 0x20, 0x58, 0x00, 0x03,
+ 0x00, 0x32, 0x00, 0x08, 0x04, 0x82, 0x00, 0x80,
+ 0x0c, 0x20, 0x02, 0x88, 0x0d, 0x2a, 0x01, 0x18,
+ 0x04, 0x5c, 0x00, 0x80, 0x00, 0x54, 0x00, 0x00,
+ 0x01, 0x62, 0x00, 0x09, 0x03, 0x64, 0x00, 0x18,
+ 0x00, 0x82, 0x00, 0x80, 0x0c, 0x20, 0x02, 0x88,
+ 0x0d, 0x2a, 0x01, 0x18, 0x04, 0x5c, 0x00, 0x80,
+ 0x00, 0x52, 0x00, 0x08, 0x00, 0x54, 0x00, 0x00,
+ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x4f,
+};
+
+/* Config tag constants */
+#define TCODE_TAG 0x5C
+#define DAC_L_TAG 0x220
+#define DELTA_DOWN_TAG 0x82
+
+/**
+ * goodix_device_get_default_config:
+ *
+ * Return a pointer to the default config and its length.
+ */
+const guint8 *
+goodix_device_get_default_config (gsize *out_len)
+{
+ *out_len = sizeof (default_config);
+ return default_config;
+}
+
+/**
+ * goodix_device_compute_otp_hash:
+ *
+ * Compute OTP hash over data using the lookup table.
+ */
+guint8
+goodix_device_compute_otp_hash (const guint8 *hash_input,
+ gsize hash_input_len)
+{
+ guint8 checksum = 0;
+
+ for (gsize i = 0; i < hash_input_len; i++)
+ checksum = otp_hash_table[checksum ^ hash_input[i]];
+
+ return ~checksum & 0xFF;
+}
+
+/**
+ * goodix_device_verify_otp:
+ *
+ * Verify OTP hash. The hash byte is at offset 25.
+ * Data for hashing = otp[0:25] + otp[26:].
+ */
+gboolean
+goodix_device_verify_otp (const guint8 *otp,
+ gsize otp_len)
+{
+ guint8 received_hash, computed_hash;
+ g_autofree guint8 *hash_input = NULL;
+ gsize hash_input_len;
+
+ if (otp_len < 27)
+ return FALSE;
+
+ received_hash = otp[25];
+
+ /* Build data = otp[:25] + otp[26:] */
+ hash_input_len = otp_len - 1;
+ hash_input = g_malloc (hash_input_len);
+ memcpy (hash_input, otp, 25);
+ memcpy (hash_input + 25, otp + 26, otp_len - 26);
+
+ computed_hash = goodix_device_compute_otp_hash (hash_input, hash_input_len);
+
+ if (received_hash != computed_hash)
+ {
+ fp_warn ("OTP hash mismatch: received 0x%02x, computed 0x%02x",
+ received_hash, computed_hash);
+ return FALSE;
+ }
+
+ fp_dbg ("OTP hash verified");
+ return TRUE;
+}
+
+/**
+ * goodix_device_parse_otp:
+ *
+ * Parse OTP data and extract calibration parameters.
+ * Ported from driver_53x5.py check_sensor().
+ */
+void
+goodix_device_parse_otp (const guint8 *otp,
+ gsize otp_len,
+ GoodixCalibParams *params)
+{
+ guint8 diff;
+ guint16 rounded_difference, scaled_difference;
+
+ memset (params, 0, sizeof (GoodixCalibParams));
+
+ params->tcode = (otp[23] != 0) ? otp[23] + 1 : 0;
+
+ diff = (otp[17] >> 1) & 0x1F;
+ fp_dbg ("OTP diff[5:1] = 0x%02x", diff);
+
+ if (diff == 0)
+ {
+ params->delta_fdt = 0;
+ params->delta_down = 0xD;
+ params->delta_up = 0xB;
+ params->delta_img = 0xC8;
+ params->delta_nav = 0x28;
+ }
+ else
+ {
+ rounded_difference = diff + 5;
+ scaled_difference = (rounded_difference * 0x32) >> 4;
+
+ params->delta_fdt = scaled_difference / 5;
+ params->delta_down = scaled_difference / 3;
+ params->delta_up = params->delta_down - 2;
+ params->delta_img = 0xC8;
+ params->delta_nav = rounded_difference * 4;
+ }
+
+ if (otp[17] == 0 || otp[22] == 0 || (otp_len > 31 ? otp[31] == 0 : TRUE))
+ {
+ params->dac_h = 0x97;
+ params->dac_l = 0xD0;
+ }
+ else
+ {
+ params->dac_h = ((guint16) otp[17] << 8 ^ otp[22]) & 0x1FF;
+ params->dac_l = ((otp[17] & 0x40) << 2) ^ otp[31];
+ params->dac_from_otp = TRUE;
+ }
+
+ if (params->tcode != 0)
+ params->dac_delta = 0xC83 / params->tcode;
+ else
+ params->dac_delta = 0;
+
+ fp_dbg ("tcode=0x%x delta_down=0x%x delta_up=0x%x "
+ "delta_img=0x%x delta_nav=0x%x dac_h=0x%x dac_l=0x%x",
+ params->tcode, params->delta_down, params->delta_up,
+ params->delta_img, params->delta_nav,
+ params->dac_h, params->dac_l);
+}
+
+/**
+ * replace_value_in_section:
+ *
+ * Replace a tagged value in a config section.
+ */
+static void
+replace_value_in_section (guint8 *config,
+ gsize config_len,
+ int section_num,
+ guint16 tag,
+ guint16 value)
+{
+ const guint8 *section_table = config + 1;
+ guint8 section_base = section_table[section_num * 2];
+ guint8 section_size = section_table[section_num * 2 + 1];
+
+ for (int entry_base = section_base;
+ entry_base < section_base + section_size;
+ entry_base += 4)
+ {
+ guint16 entry_tag = config[entry_base] |
+ ((guint16) config[entry_base + 1] << 8);
+ if (entry_tag == tag)
+ {
+ config[entry_base + 2] = value & 0xFF;
+ config[entry_base + 3] = (value >> 8) & 0xFF;
+ }
+ }
+}
+
+/**
+ * goodix_device_fix_config_checksum:
+ *
+ * Recompute and fix the 2-byte checksum at the end of the config.
+ */
+void
+goodix_device_fix_config_checksum (guint8 *config,
+ gsize config_len)
+{
+ guint32 checksum = 0xA5A5;
+
+ for (gsize i = 0; i < config_len - 2; i += 2)
+ {
+ guint16 config_word = config[i] | ((guint16) config[i + 1] << 8);
+ checksum += config_word;
+ checksum &= 0xFFFF;
+ }
+
+ checksum = 0x10000 - checksum;
+ config[config_len - 2] = checksum & 0xFF;
+ config[config_len - 1] = (checksum >> 8) & 0xFF;
+}
+
+/**
+ * goodix_device_patch_config:
+ *
+ * Apply calibration parameters to the config buffer.
+ */
+void
+goodix_device_patch_config (guint8 *config,
+ gsize config_len,
+ const GoodixCalibParams *params)
+{
+ if (params->tcode != 0)
+ {
+ replace_value_in_section (config, config_len, 2, TCODE_TAG, params->tcode);
+ replace_value_in_section (config, config_len, 3, TCODE_TAG, params->tcode);
+ replace_value_in_section (config, config_len, 4, TCODE_TAG, params->tcode);
+ }
+ if (params->dac_from_otp)
+ {
+ replace_value_in_section (config, config_len, 2, DAC_L_TAG,
+ (params->dac_l << 4) | 8);
+ replace_value_in_section (config, config_len, 3, DAC_L_TAG,
+ (params->dac_l << 4) | 8);
+ }
+ replace_value_in_section (config, config_len, 2, DELTA_DOWN_TAG,
+ (params->delta_down << 8) | 0x80);
+
+ goodix_device_fix_config_checksum (config, config_len);
+}
+
+/**
+ * goodix_device_is_fdt_base_valid:
+ *
+ * Compare two FDT data arrays and check if the max delta is within bounds.
+ * Each pair of bytes is a 16-bit LE value, compared as (val >> 1).
+ */
+gboolean
+goodix_device_is_fdt_base_valid (const guint8 *first_base,
+ const guint8 *second_base,
+ gsize len,
+ guint16 max_delta)
+{
+ for (gsize i = 0; i < len; i += 2)
+ {
+ guint16 first_sample = first_base[i] | ((guint16) first_base[i + 1] << 8);
+ guint16 second_sample = second_base[i] | ((guint16) second_base[i + 1] << 8);
+ gint delta = abs ((gint) (second_sample >> 1) - (gint) (first_sample >> 1));
+
+ if ((guint16) delta > max_delta)
+ {
+ fp_dbg ("FDT delta %d exceeds max %d at offset %zu",
+ delta, max_delta, i);
+ return FALSE;
+ }
+ }
+
+ return TRUE;
+}
+
+/**
+ * goodix_device_generate_fdt_base:
+ *
+ * Generate FDT base from FDT event data.
+ * For each 16-bit LE pair:
+ * fdt_base_val = (val & 0xFFFE) * 0x80 + (val >> 1)
+ */
+void
+goodix_device_generate_fdt_base (const guint8 *fdt_data,
+ gsize len,
+ guint8 *fdt_base)
+{
+ for (gsize i = 0; i < len; i += 2)
+ {
+ guint16 fdt_sample = fdt_data[i] | ((guint16) fdt_data[i + 1] << 8);
+ guint16 fdt_base_word = (guint16) (((fdt_sample & 0xFFFE) * 0x80) + (fdt_sample >> 1));
+
+ fdt_base[i] = fdt_base_word & 0xFF;
+ fdt_base[i + 1] = (fdt_base_word >> 8) & 0xFF;
+ }
+}
+
+/**
+ * goodix_device_generate_fdt_up_base:
+ *
+ * Generate FDT "up" base from event data and touch flag.
+ * Ported from driver_53x5.py generate_fdt_up_base().
+ */
+void
+goodix_device_generate_fdt_up_base (const guint8 *fdt_data,
+ guint16 touch_flag,
+ const GoodixCalibParams *params,
+ guint8 *fdt_base_up)
+{
+ guint16 fdt_samples[12];
+ guint16 fdt_up_base_words[12];
+
+ for (int i = 0; i < 12; i++)
+ fdt_samples[i] = fdt_data[i * 2] | ((guint16) fdt_data[i * 2 + 1] << 8);
+
+ for (int i = 0; i < 12; i++)
+ {
+ guint16 adjusted_sample = (fdt_samples[i] >> 1) + params->delta_down;
+ fdt_up_base_words[i] = (guint16) (adjusted_sample * 0x100 | adjusted_sample);
+ }
+
+ for (int i = 0; i < 12; i++)
+ {
+ if (((touch_flag >> i) & 1) == 0)
+ fdt_up_base_words[i] = (guint16) (params->delta_up * 0x100 |
+ params->delta_up);
+ }
+
+ for (int i = 0; i < 12; i++)
+ {
+ fdt_base_up[i * 2] = fdt_up_base_words[i] & 0xFF;
+ fdt_base_up[i * 2 + 1] = (fdt_up_base_words[i] >> 8) & 0xFF;
+ }
+}
diff --git a/libfprint/drivers/goodix53x5/device/calibration.h b/libfprint/drivers/goodix53x5/device/calibration.h
new file mode 100644
index 0000000..c6708ce
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/calibration.h
@@ -0,0 +1,62 @@
+/*
+ * Goodix 53x5 driver for libfprint — OTP, config, and FDT base math
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#pragma once
+
+#include "driver-private.h"
+
+guint8 goodix_device_compute_otp_hash (const guint8 *hash_input,
+ gsize hash_input_len);
+
+gboolean goodix_device_verify_otp (const guint8 *otp,
+ gsize otp_len);
+
+void goodix_device_parse_otp (const guint8 *otp,
+ gsize otp_len,
+ GoodixCalibParams *params);
+
+/* Both planes contain GOODIX_SENSOR_PIXELS decoded values. Call only after a
+ * successful live read, before publishing calibration metadata. */
+void goodix_device_adjust_dac (GoodixDynamicDacState *state,
+ GoodixCalibParams *params,
+ const guint16 *live,
+ const guint16 *reference);
+
+void goodix_device_patch_config (guint8 *config,
+ gsize config_len,
+ const GoodixCalibParams *params);
+
+void goodix_device_fix_config_checksum (guint8 *config,
+ gsize config_len);
+
+gboolean goodix_device_is_fdt_base_valid (const guint8 *first_base,
+ const guint8 *second_base,
+ gsize len,
+ guint16 max_delta);
+
+void goodix_device_generate_fdt_base (const guint8 *fdt_data,
+ gsize len,
+ guint8 *fdt_base);
+
+void goodix_device_generate_fdt_up_base (const guint8 *fdt_data,
+ guint16 touch_flag,
+ const GoodixCalibParams *params,
+ guint8 *fdt_base_up);
+
+const guint8 *goodix_device_get_default_config (gsize *out_len);
diff --git a/libfprint/drivers/goodix53x5/device/commands.c b/libfprint/drivers/goodix53x5/device/commands.c
new file mode 100644
index 0000000..563485c
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/commands.c
@@ -0,0 +1,870 @@
+/*
+ * Goodix 53x5 driver for libfprint — Named device commands and reply parsers
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/transport.h"
+#include "device/commands.h"
+#include "device/calibration.h"
+#include "device/scan.h"
+
+#include <string.h>
+
+#define GOODIX_PROTO_CMD_IMAGE 0x00
+
+/* HV value for image capture */
+#define GOODIX_HV_VALUE 6
+
+typedef struct
+{
+ FpiSsm *ssm;
+ GoodixCmdResultCallback result;
+ gboolean sleep;
+} GoodixCommandCompletion;
+
+static void
+goodix_command_done (FpDevice *dev,
+ const GoodixTransportResult *result,
+ GError *error,
+ gpointer data)
+{
+ GoodixCommandCompletion *completion = data;
+ FpiSsm *ssm = completion->ssm;
+ GoodixCmdResultCallback callback = completion->result;
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ /* Milan_SetMode stores two after ChangeMode returns, including exhaustion.
+ * Host rejection/cancellation is not a completed native mode request. */
+ if (completion->sleep && (!error || result->ordinary_exhaustion))
+ self->requested_mode = GOODIX_REQUESTED_MODE_SLEEP;
+ g_free (completion);
+ if (g_error_matches (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_BUSY))
+ {
+ /* Rejection never entered the command's retry or repair workflow. */
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+ /* Interrupted writes can leave the sensor partially commanded. Composite
+ * arm/config workflows own other intermediate failures until they settle. */
+ if (result->write_cancelled)
+ self->needs_reinit = TRUE;
+ if (callback)
+ {
+ callback (ssm, dev, result->ack_status, result->ordinary_exhaustion, error);
+ }
+ else if (error)
+ {
+ if (result->ordinary_exhaustion &&
+ goodix_scan_continue_command_error (ssm, dev, error))
+ return;
+ /* The active GTLS restart owns handshake retries and terminal failure.
+ * Do not turn an intermediate attempt into a deferred full reset. */
+ if (self->profile9_fdt.owner && !self->gtls_restart_active &&
+ !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
+ self->needs_reinit = TRUE;
+ fpi_ssm_mark_failed (ssm, error);
+ }
+ else
+ {
+ fpi_ssm_next_state (ssm);
+ }
+}
+
+static void
+goodix_run_cmd_full (FpiSsm *ssm,
+ FpDevice *dev,
+ guint8 category,
+ guint8 command,
+ const guint8 *payload,
+ gsize payload_len,
+ gboolean expect_data,
+ GoodixCmdResultCallback callback,
+ gboolean idle_after_ack)
+{
+ GoodixCommandCompletion *completion = g_new0 (GoodixCommandCompletion, 1);
+ GoodixTransportRequest request = {
+ .cmd = { category, command, (guint8 *) payload, payload_len, TRUE },
+ .expect_data = expect_data,
+ .idle_after_ack = idle_after_ack,
+ };
+
+ completion->ssm = ssm;
+ completion->result = callback;
+ completion->sleep = category == 6 && command == 0;
+ goodix_transport_command (dev, &request, goodix_command_done, completion);
+}
+
+static void
+goodix_run_cmd (FpiSsm *ssm,
+ FpDevice *dev,
+ guint8 category,
+ guint8 command,
+ const guint8 *payload,
+ gsize payload_len,
+ gboolean expect_data)
+{
+ goodix_run_cmd_full (ssm, dev, category, command, payload, payload_len,
+ expect_data, NULL, FALSE);
+}
+
+static void
+goodix_run_cmd_result (FpiSsm *ssm, FpDevice *dev,
+ guint8 category, guint8 command,
+ const guint8 *payload, gsize payload_len,
+ gboolean expect_data, GoodixCmdResultCallback callback)
+{
+ goodix_run_cmd_full (ssm, dev, category, command, payload, payload_len,
+ expect_data, callback, FALSE);
+}
+
+static void
+goodix_run_cmd_ec_off (FpiSsm *ssm, FpDevice *dev,
+ const guint8 *payload, gsize payload_len)
+{
+ goodix_run_cmd_full (ssm, dev, 0x0a, 7, payload, payload_len, FALSE,
+ NULL, TRUE);
+}
+
+void
+goodix_recv_mcu (FpiSsm *ssm, FpDevice *dev, guint timeout, gsize length)
+{
+ GoodixCommandCompletion *completion = g_new0 (GoodixCommandCompletion, 1);
+
+ completion->ssm = ssm;
+ goodix_transport_wait_mcu (dev, timeout, length, goodix_command_done, completion);
+}
+
+/* ========================================================================
+ * Payload builders
+ * ======================================================================== */
+
+static void
+goodix_build_fdt_payload (guint8 op_code,
+ const guint8 *fdt_base,
+ guint8 **out_payload,
+ gsize *out_len)
+{
+ gsize len = 2 + GOODIX_FDT_BASE_LEN;
+ guint8 *payload = g_malloc (len);
+
+ payload[0] = op_code;
+ payload[1] = 1; /* always 1 */
+ memcpy (payload + 2, fdt_base, GOODIX_FDT_BASE_LEN);
+
+ *out_payload = payload;
+ *out_len = len;
+}
+
+static void
+goodix_build_image_request (gboolean tx_enable,
+ gboolean hv_enable,
+ gboolean is_finger,
+ guint16 dac,
+ guint8 *out_request)
+{
+ guint8 op_code = tx_enable ? 0x01 : 0x81;
+ guint8 hv_value = hv_enable ? GOODIX_HV_VALUE : 0x10;
+
+ if (is_finger)
+ op_code |= 0x40;
+
+ out_request[0] = op_code;
+ out_request[1] = hv_value;
+ out_request[2] = dac & 0xFF;
+ out_request[3] = (dac >> 8) & 0xFF;
+}
+
+static void
+goodix_encode_u32_le (guint8 *out, guint32 value)
+{
+ out[0] = value & 0xFF;
+ out[1] = (value >> 8) & 0xFF;
+ out[2] = (value >> 16) & 0xFF;
+ out[3] = (value >> 24) & 0xFF;
+}
+
+/* ========================================================================
+ * Named device commands
+ * ======================================================================== */
+
+void
+goodix_cmd_ping (FpiSsm *ssm, FpDevice *dev)
+{
+ goodix_cmd_probe (ssm, dev, FALSE, NULL);
+}
+
+void
+goodix_cmd_read_fw_version (FpiSsm *ssm, FpDevice *dev)
+{
+ goodix_cmd_probe (ssm, dev, TRUE, NULL);
+}
+
+void
+goodix_cmd_probe (FpiSsm *ssm, FpDevice *dev, gboolean firmware,
+ GoodixCmdResultCallback callback)
+{
+ guint8 payload[4] = { 0 };
+ gsize len = firmware ? 2 : goodix_family (FPI_DEVICE_GOODIX53X5 (dev))->protocol.wake_payload_len;
+
+ goodix_run_cmd_result (ssm, dev, firmware ? 0x0a : 0, firmware ? 4 : 0,
+ payload, len, firmware, callback);
+}
+
+void
+goodix_cmd_reset_sensor (FpiSsm *ssm, FpDevice *dev, gboolean request_irq,
+ GoodixCmdResultCallback callback)
+{
+ /* usbinterface!18001b6c8: type zero, with optional IRQ response. */
+ guint8 payload[2] = { request_irq ? 0x05 : 0x01, 0x14 };
+
+ goodix_run_cmd_result (ssm, dev, 0xA, 0x1, payload, sizeof (payload),
+ request_irq, callback);
+}
+
+static void
+goodix_cmd_reset_after_esd (FpiSsm *ssm, FpDevice *dev,
+ GoodixCmdResultCallback callback)
+{
+ guint8 payload[2] = { 2, 50 };
+
+ goodix_run_cmd_result (ssm, dev, 0x0a, 1, payload, sizeof (payload), FALSE, callback);
+}
+
+void
+goodix_cmd_read_chip_id (FpiSsm *ssm, FpDevice *dev,
+ GoodixCmdResultCallback callback)
+{
+ /* read_data(addr=0, size=4): category=0x8, command=0x1 */
+ guint8 payload[5] = {
+ 0x00, /* \x00 */
+ 0x00, 0x00, /* addr LE */
+ 0x04, 0x00, /* size LE */
+ };
+
+ goodix_run_cmd_result (ssm, dev, 0x8, 0x1, payload, sizeof (payload),
+ TRUE, callback);
+}
+
+void
+goodix_cmd_read_otp (FpiSsm *ssm, FpDevice *dev)
+{
+ /* read_otp: category=0xA, command=0x3, payload=\x00\x00 */
+ guint8 payload[2] = { 0x00, 0x00 };
+
+ goodix_run_cmd (ssm, dev, 0xA, 0x3, payload, 2, TRUE);
+}
+
+void
+goodix_cmd_production_read (FpiSsm *ssm, FpDevice *dev, guint32 read_type)
+{
+ guint8 payload[4];
+
+ goodix_encode_u32_le (payload, read_type);
+ goodix_run_cmd (ssm, dev, 0xE, 0x2, payload, 4, TRUE);
+}
+
+void
+goodix_cmd_preset_read (FpiSsm *ssm, FpDevice *dev, guint32 slot, guint32 length)
+{
+ /* Length, offset, slot and a zero word. */
+ guint8 payload[16] = { 0 };
+
+ goodix_encode_u32_le (payload, length);
+ goodix_encode_u32_le (payload + 8, slot);
+ goodix_run_cmd (ssm, dev, GOODIX_PROTO_CATEGORY_PRODUCTION, 0x2,
+ payload, sizeof (payload), TRUE);
+}
+
+void
+goodix_cmd_mcu_send (FpiSsm *ssm, FpDevice *dev, guint32 data_type,
+ const guint8 *data, gsize data_len)
+{
+ guint8 *payload;
+ gsize payload_len;
+
+ goodix_proto_build_mcu_message (data_type, data, data_len,
+ &payload, &payload_len);
+ goodix_run_cmd (ssm, dev, 0xD, 0x1, payload, payload_len, FALSE);
+ g_free (payload);
+}
+
+void
+goodix_cmd_tls_request (FpiSsm *ssm, FpDevice *dev)
+{
+ /* The sensor ACKs, then sends its ClientHello as a TLS pack. */
+ guint8 payload[2] = { 0, 0 };
+
+ goodix_run_cmd (ssm, dev, 0xD, 0x0, payload, sizeof (payload), FALSE);
+}
+
+void
+goodix_cmd_send_tls_record (FpiSsm *ssm, FpDevice *dev, GBytes *record)
+{
+ GoodixCommandCompletion *completion = g_new0 (GoodixCommandCompletion, 1);
+
+ completion->ssm = ssm;
+ goodix_transport_send_record (dev, record, goodix_command_done, completion);
+}
+
+void
+goodix_cmd_upload_config (FpiSsm *ssm, FpDevice *dev,
+ const guint8 *config, gsize config_len)
+{
+ goodix_run_cmd (ssm, dev, GOODIX_PROTO_CATEGORY_CONFIG, GOODIX_PROTO_CMD_CONFIG_DOWNLOAD,
+ config, config_len, TRUE);
+}
+
+void
+goodix_cmd_restore_config (FpiSsm *ssm, FpDevice *dev,
+ GoodixCmdResultCallback callback)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ gsize length;
+ const guint8 *config = goodix_device_get_default_config (&length);
+ g_autofree guint8 *payload = g_memdup2 (config, length);
+
+ goodix_device_patch_config (payload, length, &self->calib);
+ goodix_run_cmd_result (ssm, dev, GOODIX_PROTO_CATEGORY_CONFIG,
+ GOODIX_PROTO_CMD_CONFIG_DOWNLOAD, payload, length, TRUE, callback);
+}
+
+typedef enum {
+ GOODIX_ARM_FIRST,
+ GOODIX_ARM_CONFIG,
+ GOODIX_ARM_REPEAT,
+ GOODIX_ARM_NUM_STATES,
+} GoodixArmState;
+
+typedef struct
+{
+ FpiSsm *parent;
+ guint8 command;
+ guint8 first_base[GOODIX_FDT_BASE_LEN];
+} GoodixArmOperation;
+
+static void
+goodix_arm_result (FpiSsm *ssm, FpDevice *dev, guint8 status,
+ gboolean native_zero, GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixArmOperation *operation = fpi_ssm_get_data (ssm);
+ GoodixArmState state = fpi_ssm_get_cur_state (ssm);
+
+ if (error)
+ g_prefix_error (&error, "FDT arm parent-state=%d: ", fpi_ssm_get_cur_state (operation->parent));
+ if (error && !native_zero)
+ {
+ if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
+ self->needs_reinit = TRUE;
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+ /* Ordinary exhausted arm/config results do not reconstruct the HAL. */
+ if (error)
+ fp_dbg ("Continuing native FDT wait/repair after %s", error->message);
+ g_clear_error (&error);
+ /* The last foreground token can remain cancelled after action completion.
+ * Idle maintenance belongs to the session, including during handoff. */
+ GCancellable *cancel = self->session_cancel;
+
+ if (cancel && g_cancellable_is_cancelled (cancel))
+ {
+ /* Join a completed arm before the coordinator observes terminal stop.
+ * Cancellation still prevents configuration repair or another arm. */
+ if (state != GOODIX_ARM_CONFIG && !native_zero)
+ fpi_ssm_mark_completed (ssm);
+ else
+ fpi_ssm_mark_failed (ssm, g_error_new_literal (G_IO_ERROR, G_IO_ERROR_CANCELLED,
+ "FDT arm cancelled"));
+ return;
+ }
+ if (state == GOODIX_ARM_CONFIG ||
+ (state == GOODIX_ARM_FIRST && !native_zero &&
+ goodix_family (self)->protocol.repair_arm (status)))
+ fpi_ssm_next_state (ssm);
+ else
+ fpi_ssm_mark_completed (ssm);
+}
+
+static void
+goodix_arm_handler (FpiSsm *ssm, FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixArmOperation *operation = fpi_ssm_get_data (ssm);
+ g_autofree guint8 *payload = NULL;
+ gsize payload_len;
+
+ if (fpi_ssm_get_cur_state (ssm) == GOODIX_ARM_CONFIG)
+ {
+ const guint8 *config = goodix_device_get_default_config (&payload_len);
+ payload = g_memdup2 (config, payload_len);
+ goodix_device_patch_config (payload, payload_len, &self->calib);
+ goodix_run_cmd_result (ssm, dev, GOODIX_PROTO_CATEGORY_CONFIG,
+ GOODIX_PROTO_CMD_CONFIG_DOWNLOAD, payload, payload_len, TRUE,
+ goodix_arm_result);
+ }
+ else
+ {
+ const guint8 *base = fpi_ssm_get_cur_state (ssm) == GOODIX_ARM_FIRST ?
+ operation->first_base : operation->command == GOODIX_PROTO_CMD_FDT_DOWN ?
+ self->profile9_fdt.base_down : self->profile9_fdt.base_up;
+ goodix_build_fdt_payload (operation->command == GOODIX_PROTO_CMD_FDT_DOWN ? 0x0c : 0x0e,
+ base, &payload, &payload_len);
+ goodix_run_cmd_result (ssm, dev, GOODIX_PROTO_CATEGORY_FDT, operation->command,
+ payload, payload_len, FALSE, goodix_arm_result);
+ }
+}
+
+static void
+goodix_arm_start (FpiSsm *parent, FpDevice *dev, guint8 command, const guint8 *base)
+{
+ GoodixArmOperation *operation = g_new0 (GoodixArmOperation, 1);
+ FpiSsm *ssm = fpi_ssm_new (dev, goodix_arm_handler, GOODIX_ARM_NUM_STATES);
+
+ operation->command = command;
+ operation->parent = parent;
+ memcpy (operation->first_base, base, sizeof (operation->first_base));
+ fpi_ssm_set_data (ssm, operation, g_free);
+ fpi_ssm_start_subsm (parent, ssm);
+}
+
+void
+goodix_cmd_fdt_down_setup (FpiSsm *ssm, FpDevice *dev, const guint8 *fdt_base)
+{
+ goodix_arm_start (ssm, dev, GOODIX_PROTO_CMD_FDT_DOWN, fdt_base);
+}
+
+void
+goodix_cmd_fdt_up_setup (FpiSsm *ssm, FpDevice *dev, const guint8 *fdt_base)
+{
+ goodix_arm_start (ssm, dev, GOODIX_PROTO_CMD_FDT_UP, fdt_base);
+}
+
+typedef enum {
+ GOODIX_ESD_RESET,
+ GOODIX_ESD_RESET_AGAIN,
+ GOODIX_ESD_CHIP,
+ GOODIX_ESD_FAILED_READ_RESET,
+ GOODIX_ESD_RETRY,
+ GOODIX_ESD_EXHAUSTED_RESET,
+ GOODIX_ESD_CONFIG,
+ GOODIX_ESD_ARM,
+ GOODIX_ESD_DONE,
+ GOODIX_ESD_NUM_STATES,
+} GoodixEsdState;
+
+typedef struct
+{
+ guint attempts;
+ gboolean notice_mask;
+ guint32 chip;
+} GoodixEsdOperation;
+
+static void
+goodix_esd_result (FpiSsm *ssm, FpDevice *dev, guint8 status,
+ gboolean native_zero, GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixEsdOperation *data = fpi_ssm_get_data (ssm);
+ gboolean success = error == NULL;
+
+ if (error && !native_zero)
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+ g_clear_error (&error);
+ switch (fpi_ssm_get_cur_state (ssm))
+ {
+ case GOODIX_ESD_RESET:
+ if (data->notice_mask)
+ fpi_ssm_jump_to_state_delayed (ssm, GOODIX_ESD_CHIP, 6);
+ else if (success && (((guint) self->shared_response[1] |
+ ((guint) self->shared_response[2] << 8)) == 0x410))
+ fpi_ssm_jump_to_state (ssm, GOODIX_ESD_RESET_AGAIN);
+ else
+ fpi_ssm_jump_to_state_delayed (ssm, GOODIX_ESD_RETRY, 200);
+ break;
+
+ case GOODIX_ESD_RESET_AGAIN:
+ fpi_ssm_jump_to_state_delayed (ssm, GOODIX_ESD_CHIP, 6);
+ break;
+
+ case GOODIX_ESD_CHIP:
+ if (success)
+ {
+ const guint8 *bytes = self->shared_response;
+ data->chip = ((guint32) bytes[0] << 8) | bytes[1] |
+ ((guint32) bytes[2] << 24) | ((guint32) bytes[3] << 16);
+ }
+ if ((!data->notice_mask || success) && data->chip == self->chip_id)
+ fpi_ssm_jump_to_state (ssm, GOODIX_ESD_CONFIG);
+ else if (data->notice_mask && !success)
+ fpi_ssm_jump_to_state (ssm, GOODIX_ESD_FAILED_READ_RESET);
+ else
+ fpi_ssm_jump_to_state_delayed (ssm, GOODIX_ESD_RETRY, 200);
+ break;
+
+ case GOODIX_ESD_FAILED_READ_RESET:
+ fpi_ssm_jump_to_state_delayed (ssm, GOODIX_ESD_RETRY, 200);
+ break;
+
+ case GOODIX_ESD_CONFIG:
+ fpi_ssm_jump_to_state (ssm, GOODIX_ESD_ARM);
+ break;
+
+ case GOODIX_ESD_EXHAUSTED_RESET:
+ fpi_ssm_jump_to_state (ssm, GOODIX_ESD_DONE);
+ break;
+
+ default:
+ g_assert_not_reached ();
+ }
+}
+
+static void
+goodix_esd_handler (FpiSsm *ssm, FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixEsdOperation *data = fpi_ssm_get_data (ssm);
+
+ switch (fpi_ssm_get_cur_state (ssm))
+ {
+ case GOODIX_ESD_RESET:
+ data->attempts++;
+ G_GNUC_FALLTHROUGH;
+
+ case GOODIX_ESD_RESET_AGAIN:
+ case GOODIX_ESD_FAILED_READ_RESET:
+ goodix_cmd_reset_sensor (ssm, dev, TRUE, goodix_esd_result);
+ break;
+
+ case GOODIX_ESD_CHIP:
+ goodix_cmd_read_chip_id (ssm, dev, goodix_esd_result);
+ break;
+
+ case GOODIX_ESD_RETRY:
+ fpi_ssm_jump_to_state (ssm, data->attempts < 10 ? GOODIX_ESD_RESET : GOODIX_ESD_EXHAUSTED_RESET);
+ break;
+
+ case GOODIX_ESD_EXHAUSTED_RESET:
+ goodix_cmd_reset_after_esd (ssm, dev, goodix_esd_result);
+ break;
+
+ case GOODIX_ESD_CONFIG:
+ goodix_cmd_restore_config (ssm, dev, goodix_esd_result);
+ break;
+
+ case GOODIX_ESD_ARM:
+ /* Native missing-file loader preserves RAM bases/image/validity/marker.
+ * No OTP, GTLS, dynamic DAC reseeding or reference capture belongs here. */
+ self->profile9_fdt.wait_mode = GOODIX_PROFILE9_FDT_WAIT_DOWN;
+ goodix_cmd_fdt_down_setup (ssm, dev, self->profile9_fdt.base_down);
+ break;
+
+ case GOODIX_ESD_DONE:
+ fpi_ssm_mark_completed (ssm);
+ break;
+
+ default:
+ g_assert_not_reached ();
+ }
+}
+
+void
+goodix_cmd_repair_esd (FpiSsm *parent, FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixEsdOperation *data = g_new0 (GoodixEsdOperation, 1);
+ FpiSsm *ssm = fpi_ssm_new (dev, goodix_esd_handler, GOODIX_ESD_NUM_STATES);
+
+ data->notice_mask = ((self->notice_irq[0] | ((guint16) self->notice_irq[1] << 8)) & 0x410) != 0;
+ fpi_ssm_set_data (ssm, data, g_free);
+ fpi_ssm_start_subsm (parent, ssm);
+}
+
+void
+goodix_cmd_fdt_manual (FpiSsm *ssm, FpDevice *dev,
+ gboolean tx_enable, const guint8 *fdt_base)
+{
+ goodix_cmd_fdt_manual_result (ssm, dev, tx_enable, fdt_base, NULL);
+}
+
+void
+goodix_cmd_fdt_manual_result (FpiSsm *ssm, FpDevice *dev,
+ gboolean tx_enable, const guint8 *fdt_base,
+ GoodixCmdResultCallback callback)
+{
+ /* Manual FDT op code: 0x0D with TX enabled, 0x8D with TX disabled */
+ guint8 op_code = tx_enable ? 0x0D : 0x8D;
+ guint8 *payload;
+ gsize payload_len;
+
+ goodix_build_fdt_payload (op_code, fdt_base, &payload, &payload_len);
+ goodix_run_cmd_result (ssm, dev, GOODIX_PROTO_CATEGORY_FDT,
+ GOODIX_PROTO_CMD_FDT_MANUAL, payload, payload_len, TRUE, callback);
+ g_free (payload);
+}
+
+void
+goodix_cmd_request_image (FpiSsm *ssm, FpDevice *dev,
+ gboolean tx_enable, gboolean hv_enable,
+ gboolean is_finger, guint16 dac)
+{
+ goodix_cmd_request_image_result (ssm, dev, tx_enable, hv_enable, is_finger, dac, NULL);
+}
+
+void
+goodix_cmd_request_image_result (FpiSsm *ssm, FpDevice *dev,
+ gboolean tx_enable, gboolean hv_enable,
+ gboolean is_finger, guint16 dac,
+ GoodixCmdResultCallback callback)
+{
+ guint8 img_req[4];
+
+ goodix_build_image_request (tx_enable, hv_enable, is_finger, dac, img_req);
+ goodix_run_cmd_result (ssm, dev, GOODIX_PROTO_CATEGORY_IMAGE, GOODIX_PROTO_CMD_IMAGE,
+ img_req, sizeof (img_req), TRUE, callback);
+}
+
+void
+goodix_cmd_set_sleep_mode (FpiSsm *ssm, FpDevice *dev)
+{
+ goodix_cmd_set_sleep_mode_result (ssm, dev, NULL);
+}
+
+void
+goodix_cmd_set_sleep_mode_result (FpiSsm *ssm, FpDevice *dev,
+ GoodixCmdResultCallback callback)
+{
+ /* set_sleep_mode: category=0x6, command=0, payload=\x01\x00 */
+ guint8 payload[2] = { 0x01, 0x00 };
+
+ goodix_run_cmd_result (ssm, dev, 0x6, 0x0, payload, 2, FALSE, callback);
+}
+
+void
+goodix_cmd_ec_control (FpiSsm *ssm, FpDevice *dev, gboolean on)
+{
+ guint8 payload_on[3];
+ guint8 payload_off[3] = { 0x00, 0x00, 0x00 };
+
+ memcpy (payload_on, goodix_family (FPI_DEVICE_GOODIX53X5 (dev))->protocol.ec_on_payload,
+ sizeof (payload_on));
+ if (on)
+ goodix_run_cmd (ssm, dev, 0xA, 0x7, payload_on, 3, FALSE);
+ else
+ goodix_run_cmd_ec_off (ssm, dev, payload_off, sizeof (payload_off));
+}
+
+/* ========================================================================
+ * Named reply parsers
+ * ======================================================================== */
+
+gboolean
+goodix_cmd_parse_fw_version_reply (FpDevice *dev,
+ const guint8 **out_payload,
+ gsize *out_payload_len,
+ GError **error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (!(self->command_response_ready & 4))
+ {
+ g_set_error_literal (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "Firmware response is unavailable");
+ return FALSE;
+ }
+ if (out_payload)
+ *out_payload = self->shared_response;
+ if (out_payload_len)
+ *out_payload_len = sizeof (self->shared_response);
+ return TRUE;
+}
+
+gboolean
+goodix_cmd_parse_chip_id_reply (FpDevice *dev,
+ const guint8 **out_payload,
+ gsize *out_payload_len,
+ GError **error)
+{
+ return goodix_parse_reply_exact (dev, 0x8, 0x1, out_payload,
+ out_payload_len, error);
+}
+
+gboolean
+goodix_cmd_parse_otp_reply (FpDevice *dev,
+ const guint8 **out_payload,
+ gsize *out_payload_len,
+ GError **error)
+{
+ return goodix_parse_reply_exact (dev, 0xA, 0x3, out_payload,
+ out_payload_len, error);
+}
+
+gboolean
+goodix_cmd_parse_production_read_reply (FpDevice *dev,
+ guint32 read_type,
+ const guint8 **out_data,
+ gsize *out_data_len)
+{
+ const guint8 *payload;
+ gsize payload_len;
+
+ return goodix_parse_reply_exact (dev, 0xE, 0x2, &payload, &payload_len,
+ NULL) &&
+ goodix_proto_parse_production_read (payload, payload_len, read_type,
+ out_data, out_data_len);
+}
+
+gboolean
+goodix_cmd_parse_mcu_reply (FpDevice *dev,
+ guint32 expected_type,
+ const guint8 **out_data,
+ gsize *out_data_len)
+{
+ guint8 category, command;
+ const guint8 *payload;
+ gsize payload_len;
+
+ return goodix_parse_reply (dev, &category, &command, &payload,
+ &payload_len, NULL) &&
+ goodix_proto_parse_mcu_message (payload, payload_len, expected_type,
+ out_data, out_data_len);
+}
+
+gboolean
+goodix_cmd_parse_config_reply (FpDevice *dev)
+{
+ /* Transport validated the packet and published native selector 1. Its
+ * payload is scratch, not a retained configuration success byte. */
+ return (FPI_DEVICE_GOODIX53X5 (dev)->command_response_ready & 2) != 0;
+}
+
+gboolean
+goodix_cmd_parse_fdt_manual_reply (FpDevice *dev,
+ const guint8 **out_payload,
+ gsize *out_payload_len,
+ GError **error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (!(self->command_response_ready & 1))
+ {
+ g_set_error_literal (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "Manual FDT response is not ready");
+ return FALSE;
+ }
+ *out_payload = self->manual_response;
+ *out_payload_len = sizeof (self->manual_response);
+ return TRUE;
+}
+
+guint16 *
+goodix_cmd_dup_image_reply (FpDevice *dev,
+ GError **error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (!(self->command_response_ready & 8) || !self->image_response ||
+ self->image_response_failed)
+ {
+ g_set_error_literal (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "Image response is unavailable");
+ return NULL;
+ }
+ return g_memdup2 (self->image_response, GOODIX_SENSOR_PIXELS * sizeof (guint16));
+}
+
+gboolean
+goodix_cmd_parse_fdt_event (FpDevice *dev,
+ GoodixProfile9FdtWaitMode armed_mode,
+ GoodixFdtEventType *out_type,
+ GoodixProfile9FdtEvent *out_event,
+ GError **error)
+{
+ guint8 category, command;
+ guint8 expected_command;
+ const guint8 *payload;
+ gsize payload_len;
+ g_autoptr(GError) event_error = NULL;
+
+ g_return_val_if_fail (out_type != NULL, FALSE);
+ g_return_val_if_fail (out_event != NULL, FALSE);
+
+ if (armed_mode == GOODIX_PROFILE9_FDT_WAIT_DOWN)
+ {
+ expected_command = GOODIX_PROTO_CMD_FDT_DOWN;
+ }
+ else if (armed_mode == GOODIX_PROFILE9_FDT_WAIT_UP)
+ {
+ expected_command = GOODIX_PROTO_CMD_FDT_UP;
+ }
+ else
+ {
+ g_set_error_literal (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "FDT event arrived without an armed command");
+ return FALSE;
+ }
+
+ if (!goodix_parse_reply (dev, &category, &command, &payload,
+ &payload_len, NULL))
+ {
+ g_set_error (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "Failed to parse FDT event");
+ return FALSE;
+ }
+
+ /* [irq_status(2)][touch_flag(2)][fdt_data(GOODIX_FDT_BASE_LEN)] */
+ if (category != GOODIX_PROTO_CATEGORY_FDT ||
+ command != expected_command)
+ {
+ g_set_error (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "Unexpected FDT event: armed=0x%02x cat=0x%02x cmd=0x%02x len=%zu",
+ expected_command, category, command, payload_len);
+ return FALSE;
+ }
+
+ *out_type = goodix_family (FPI_DEVICE_GOODIX53X5 (dev))->protocol.fdt_event (
+ FPI_DEVICE_GOODIX53X5 (dev), payload, payload_len, &event_error);
+ if (event_error)
+ {
+ g_propagate_error (error, g_steal_pointer (&event_error));
+ return FALSE;
+ }
+ if (*out_type == GOODIX_FDT_EVENT_NONE)
+ {
+ out_event->pending = FALSE;
+ return TRUE;
+ }
+ out_event->irq = payload[0] | ((guint16) payload[1] << 8);
+ if (*out_type == GOODIX_FDT_EVENT_CONFIG)
+ {
+ out_event->pending = TRUE;
+ return TRUE;
+ }
+
+ out_event->touch_flag = payload[2] | ((guint16) payload[3] << 8);
+ memcpy (out_event->raw, payload + 4, GOODIX_FDT_BASE_LEN);
+ out_event->pending = TRUE;
+
+ return TRUE;
+}
diff --git a/libfprint/drivers/goodix53x5/device/commands.h b/libfprint/drivers/goodix53x5/device/commands.h
new file mode 100644
index 0000000..5b66ca7
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/commands.h
@@ -0,0 +1,185 @@
+/*
+ * Goodix 53x5 driver for libfprint — Named device commands and reply parsers
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#pragma once
+
+#include "driver-private.h"
+
+/* ========================================================================
+ * Named device commands
+ *
+ * These wrap goodix_run_cmd() so action modules read as device operations
+ * instead of category/command bytes and hand-built payloads. Commands that
+ * expect a data reply have a matching named reply parser below; commands
+ * documented as "ACK only" advance the parent SSM after ACK validation.
+ * ======================================================================== */
+
+/* Ping the MCU. ACK only. */
+void goodix_cmd_ping (FpiSsm *ssm, FpDevice *dev);
+
+/* Composite owners distinguish ordinary exhausted transactions from terminal
+ * protocol/host errors. Callback takes error ownership and resolves ssm. */
+typedef void (*GoodixCmdResultCallback) (FpiSsm *ssm, FpDevice *dev,
+ guint8 status, gboolean native_zero,
+ GError *error);
+
+/* Read the firmware version string. Expects data. */
+void goodix_cmd_read_fw_version (FpiSsm *ssm, FpDevice *dev);
+void goodix_cmd_probe (FpiSsm *ssm, FpDevice *dev, gboolean firmware,
+ GoodixCmdResultCallback callback);
+
+/* Reset type 0. With @request_irq, wait for the shared reset/version response
+ * event as well as ACK; startup recovery discards the returned IRQ bytes. */
+void goodix_cmd_reset_sensor (FpiSsm *ssm, FpDevice *dev, gboolean request_irq,
+ GoodixCmdResultCallback callback);
+
+/* Read 4 bytes of chip ID from register address 0. Expects data. */
+void goodix_cmd_read_chip_id (FpiSsm *ssm, FpDevice *dev,
+ GoodixCmdResultCallback callback);
+
+/* Read the OTP calibration block. Expects data. */
+void goodix_cmd_read_otp (FpiSsm *ssm, FpDevice *dev);
+
+/* Production read of @read_type (e.g. 0xB003 = PSK hash). Expects data. */
+void goodix_cmd_production_read (FpiSsm *ssm, FpDevice *dev,
+ guint32 read_type);
+
+/* Send an MCU envelope of @data_type (GTLS handshake traffic). ACK only;
+ * the device replies asynchronously via a plain receive. */
+void goodix_cmd_mcu_send (FpiSsm *ssm, FpDevice *dev, guint32 data_type,
+ const guint8 *data, gsize data_len);
+
+/* Post-MCU-ACK GTLS wait; consume the bounded stream after its receive signal. */
+void goodix_recv_mcu (FpiSsm *ssm, FpDevice *dev, guint timeout, gsize length);
+
+/* GM168SEC sensors (27c6:533c) only. */
+/* Reads @length bytes of preset @slot; the reply has production_read's
+ * layout, so goodix_cmd_parse_production_read_reply() reads it. */
+void goodix_cmd_preset_read (FpiSsm *ssm, FpDevice *dev, guint32 slot,
+ guint32 length);
+void goodix_cmd_tls_request (FpiSsm *ssm, FpDevice *dev);
+/* Sends a TLS record to the sensor; completes once written, as the sensor
+ * never ACKs one. */
+void goodix_cmd_send_tls_record (FpiSsm *ssm, FpDevice *dev, GBytes *record);
+
+/* Upload the (patched) sensor config blob. Waits for the configuration event;
+ * its payload is not a success flag. */
+void goodix_cmd_upload_config (FpiSsm *ssm, FpDevice *dev,
+ const guint8 *config, gsize config_len);
+
+/* Native mode 4: restore the profile configuration using retained calibration. */
+void goodix_cmd_restore_config (FpiSsm *ssm, FpDevice *dev,
+ GoodixCmdResultCallback callback);
+
+/* Category-C/0 GFESD repair, native missing-saved-file/RAM continuation. */
+void goodix_cmd_repair_esd (FpiSsm *ssm, FpDevice *dev);
+
+/* Arm finger-down detection with @fdt_base. ACK only; the FDT event arrives
+ * later via a cancellable receive. */
+void goodix_cmd_fdt_down_setup (FpiSsm *ssm, FpDevice *dev,
+ const guint8 *fdt_base);
+
+/* Arm finger-up detection with @fdt_base. ACK only; the FDT event arrives
+ * later via a cancellable receive. */
+void goodix_cmd_fdt_up_setup (FpiSsm *ssm, FpDevice *dev,
+ const guint8 *fdt_base);
+
+/* Run a manual FDT check against @fdt_base, with sensor TX on or off.
+ * Expects data (irq status, touch flag and live FDT data). */
+void goodix_cmd_fdt_manual (FpiSsm *ssm, FpDevice *dev,
+ gboolean tx_enable, const guint8 *fdt_base);
+void goodix_cmd_fdt_manual_result (FpiSsm *ssm, FpDevice *dev,
+ gboolean tx_enable, const guint8 *fdt_base,
+ GoodixCmdResultCallback callback);
+
+/* Request an image frame. Expects data (the encrypted frame). */
+void goodix_cmd_request_image (FpiSsm *ssm, FpDevice *dev,
+ gboolean tx_enable, gboolean hv_enable,
+ gboolean is_finger, guint16 dac);
+void goodix_cmd_request_image_result (FpiSsm *ssm, FpDevice *dev,
+ gboolean tx_enable, gboolean hv_enable,
+ gboolean is_finger, guint16 dac,
+ GoodixCmdResultCallback callback);
+
+/* Put the MCU into sleep mode. ACK only. */
+void goodix_cmd_set_sleep_mode (FpiSsm *ssm, FpDevice *dev);
+void goodix_cmd_set_sleep_mode_result (FpiSsm *ssm, FpDevice *dev,
+ GoodixCmdResultCallback callback);
+
+/* Switch sensor EC power on or off. ACK only; off enables idle tail servicing. */
+void goodix_cmd_ec_control (FpiSsm *ssm, FpDevice *dev, gboolean on);
+
+/* ========================================================================
+ * Named reply parsers
+ *
+ * Payload pointers borrow the transport's validated reply view. Shared-response
+ * commands consume parser cache bytes, even when data arrived before ACK.
+ * Firmware uses that same cache; manual FDT uses its own. Consume borrowed
+ * views before the next receive/invalidation can replace them.
+ * ======================================================================== */
+
+gboolean goodix_cmd_parse_fw_version_reply (FpDevice *dev,
+ const guint8 **out_payload,
+ gsize *out_payload_len,
+ GError **error);
+
+gboolean goodix_cmd_parse_chip_id_reply (FpDevice *dev,
+ const guint8 **out_payload,
+ gsize *out_payload_len,
+ GError **error);
+
+gboolean goodix_cmd_parse_otp_reply (FpDevice *dev,
+ const guint8 **out_payload,
+ gsize *out_payload_len,
+ GError **error);
+
+gboolean goodix_cmd_parse_production_read_reply (FpDevice *dev,
+ guint32 read_type,
+ const guint8 **out_data,
+ gsize *out_data_len);
+
+gboolean goodix_cmd_parse_mcu_reply (FpDevice *dev,
+ guint32 expected_type,
+ const guint8 **out_data,
+ gsize *out_data_len);
+
+/* TRUE if the configuration response event has been published for this send. */
+gboolean goodix_cmd_parse_config_reply (FpDevice *dev);
+
+/* Parse a manual FDT reading returned by goodix_cmd_fdt_manual(). */
+gboolean goodix_cmd_parse_fdt_manual_reply (FpDevice *dev,
+ const guint8 **out_payload,
+ gsize *out_payload_len,
+ GError **error);
+
+/* Copy the receiver-decoded frame selected by goodix_cmd_request_image().
+ * The caller owns the copy; subsequent reception cannot replace its bytes. */
+guint16 *goodix_cmd_dup_image_reply (FpDevice *dev,
+ GError **error);
+
+/* Parse an FDT down/up event delivered after goodix_cmd_fdt_down_setup() /
+ * goodix_cmd_fdt_up_setup(). The payload layout is
+ * [irq_status(2)][touch_flag(2)][fdt_data(GOODIX_FDT_BASE_LEN)]. Decoding does
+ * not apply base mutations or select the worker's pending notification.
+ * NONE writes only pending=FALSE; CONFIG writes irq/pending, with no sample. */
+gboolean goodix_cmd_parse_fdt_event (FpDevice *dev,
+ GoodixProfile9FdtWaitMode armed_mode,
+ GoodixFdtEventType *out_type,
+ GoodixProfile9FdtEvent *out_event,
+ GError **error);
diff --git a/libfprint/drivers/goodix53x5/device/crypto.c b/libfprint/drivers/goodix53x5/device/crypto.c
new file mode 100644
index 0000000..3630c23
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/crypto.c
@@ -0,0 +1,551 @@
+/*
+ * Goodix 53x5 driver for libfprint — Crypto layer
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "device/crypto.h"
+
+#include <string.h>
+#include <openssl/evp.h>
+#include <openssl/rand.h>
+
+/* CRC32-MPEG2 lookup table */
+static const guint32 crc32_mpeg2_table[256] = {
+ 0x00000000, 0x04C11DB7, 0x09823B6E, 0x0D4326D9,
+ 0x130476DC, 0x17C56B6B, 0x1A864DB2, 0x1E475005,
+ 0x2608EDB8, 0x22C9F00F, 0x2F8AD6D6, 0x2B4BCB61,
+ 0x350C9B64, 0x31CD86D3, 0x3C8EA00A, 0x384FBDBD,
+ 0x4C11DB70, 0x48D0C6C7, 0x4593E01E, 0x4152FDA9,
+ 0x5F15ADAC, 0x5BD4B01B, 0x569796C2, 0x52568B75,
+ 0x6A1936C8, 0x6ED82B7F, 0x639B0DA6, 0x675A1011,
+ 0x791D4014, 0x7DDC5DA3, 0x709F7B7A, 0x745E66CD,
+ 0x9823B6E0, 0x9CE2AB57, 0x91A18D8E, 0x95609039,
+ 0x8B27C03C, 0x8FE6DD8B, 0x82A5FB52, 0x8664E6E5,
+ 0xBE2B5B58, 0xBAEA46EF, 0xB7A96036, 0xB3687D81,
+ 0xAD2F2D84, 0xA9EE3033, 0xA4AD16EA, 0xA06C0B5D,
+ 0xD4326D90, 0xD0F37027, 0xDDB056FE, 0xD9714B49,
+ 0xC7361B4C, 0xC3F706FB, 0xCEB42022, 0xCA753D95,
+ 0xF23A8028, 0xF6FB9D9F, 0xFBB8BB46, 0xFF79A6F1,
+ 0xE13EF6F4, 0xE5FFEB43, 0xE8BCCD9A, 0xEC7DD02D,
+ 0x34867077, 0x30476DC0, 0x3D044B19, 0x39C556AE,
+ 0x278206AB, 0x23431B1C, 0x2E003DC5, 0x2AC12072,
+ 0x128E9DCF, 0x164F8078, 0x1B0CA6A1, 0x1FCDBB16,
+ 0x018AEB13, 0x054BF6A4, 0x0808D07D, 0x0CC9CDCA,
+ 0x7897AB07, 0x7C56B6B0, 0x71159069, 0x75D48DDE,
+ 0x6B93DDDB, 0x6F52C06C, 0x6211E6B5, 0x66D0FB02,
+ 0x5E9F46BF, 0x5A5E5B08, 0x571D7DD1, 0x53DC6066,
+ 0x4D9B3063, 0x495A2DD4, 0x44190B0D, 0x40D816BA,
+ 0xACA5C697, 0xA864DB20, 0xA527FDF9, 0xA1E6E04E,
+ 0xBFA1B04B, 0xBB60ADFC, 0xB6238B25, 0xB2E29692,
+ 0x8AAD2B2F, 0x8E6C3698, 0x832F1041, 0x87EE0DF6,
+ 0x99A95DF3, 0x9D684044, 0x902B669D, 0x94EA7B2A,
+ 0xE0B41DE7, 0xE4750050, 0xE9362689, 0xEDF73B3E,
+ 0xF3B06B3B, 0xF771768C, 0xFA325055, 0xFEF34DE2,
+ 0xC6BCF05F, 0xC27DEDE8, 0xCF3ECB31, 0xCBFFD686,
+ 0xD5B88683, 0xD1799B34, 0xDC3ABDED, 0xD8FBA05A,
+ 0x690CE0EE, 0x6DCDFD59, 0x608EDB80, 0x644FC637,
+ 0x7A089632, 0x7EC98B85, 0x738AAD5C, 0x774BB0EB,
+ 0x4F040D56, 0x4BC510E1, 0x46863638, 0x42472B8F,
+ 0x5C007B8A, 0x58C1663D, 0x558240E4, 0x51435D53,
+ 0x251D3B9E, 0x21DC2629, 0x2C9F00F0, 0x285E1D47,
+ 0x36194D42, 0x32D850F5, 0x3F9B762C, 0x3B5A6B9B,
+ 0x0315D626, 0x07D4CB91, 0x0A97ED48, 0x0E56F0FF,
+ 0x1011A0FA, 0x14D0BD4D, 0x19939B94, 0x1D528623,
+ 0xF12F560E, 0xF5EE4BB9, 0xF8AD6D60, 0xFC6C70D7,
+ 0xE22B20D2, 0xE6EA3D65, 0xEBA91BBC, 0xEF68060B,
+ 0xD727BBB6, 0xD3E6A601, 0xDEA580D8, 0xDA649D6F,
+ 0xC423CD6A, 0xC0E2D0DD, 0xCDA1F604, 0xC960EBB3,
+ 0xBD3E8D7E, 0xB9FF90C9, 0xB4BCB610, 0xB07DABA7,
+ 0xAE3AFBA2, 0xAAFBE615, 0xA7B8C0CC, 0xA379DD7B,
+ 0x9B3660C6, 0x9FF77D71, 0x92B45BA8, 0x9675461F,
+ 0x8832161A, 0x8CF30BAD, 0x81B02D74, 0x857130C3,
+ 0x5D8A9099, 0x594B8D2E, 0x5408ABF7, 0x50C9B640,
+ 0x4E8EE645, 0x4A4FFBF2, 0x470CDD2B, 0x43CDC09C,
+ 0x7B827D21, 0x7F436096, 0x7200464F, 0x76C15BF8,
+ 0x68860BFD, 0x6C47164A, 0x61043093, 0x65C52D24,
+ 0x119B4BE9, 0x155A565E, 0x18197087, 0x1CD86D30,
+ 0x029F3D35, 0x065E2082, 0x0B1D065B, 0x0FDC1BEC,
+ 0x3793A651, 0x3352BBE6, 0x3E119D3F, 0x3AD08088,
+ 0x2497D08D, 0x2056CD3A, 0x2D15EBE3, 0x29D4F654,
+ 0xC5A92679, 0xC1683BCE, 0xCC2B1D17, 0xC8EA00A0,
+ 0xD6AD50A5, 0xD26C4D12, 0xDF2F6BCB, 0xDBEE767C,
+ 0xE3A1CBC1, 0xE760D676, 0xEA23F0AF, 0xEEE2ED18,
+ 0xF0A5BD1D, 0xF464A0AA, 0xF9278673, 0xFDE69BC4,
+ 0x89B8FD09, 0x8D79E0BE, 0x803AC667, 0x84FBDBD0,
+ 0x9ABC8BD5, 0x9E7D9662, 0x933EB0BB, 0x97FFAD0C,
+ 0xAFB010B1, 0xAB710D06, 0xA6322BDF, 0xA2F33668,
+ 0xBCB4666D, 0xB8757BDA, 0xB5365D03, 0xB1F740B4,
+};
+
+/**
+ * goodix_crypto_crc32_mpeg2:
+ *
+ * Compute CRC32-MPEG2 checksum.
+ */
+guint32
+goodix_crypto_crc32_mpeg2 (const guint8 *data,
+ gsize len)
+{
+ guint32 crc = 0xFFFFFFFF;
+
+ for (gsize i = 0; i < len; i++)
+ crc = (crc << 8) ^ crc32_mpeg2_table[((crc >> 24) ^ data[i]) & 0xFF];
+
+ return crc;
+}
+
+/**
+ * goodix_crypto_decode_u32:
+ *
+ * Decode a 4-byte value with the custom byte order used by the device.
+ * data[0]*0x100 + data[1] + data[2]*0x1000000 + data[3]*0x10000
+ */
+guint32
+goodix_crypto_decode_u32 (const guint8 *data)
+{
+ return (guint32) data[0] * 0x100 +
+ (guint32) data[1] +
+ (guint32) data[2] * 0x1000000 +
+ (guint32) data[3] * 0x10000;
+}
+
+/**
+ * goodix_crypto_hmac_sha256:
+ *
+ * Compute HMAC-SHA256 using GLib's GHmac.
+ * Output is always 32 bytes.
+ */
+void
+goodix_crypto_hmac_sha256 (const guint8 *key,
+ gsize key_len,
+ const guint8 *data,
+ gsize data_len,
+ guint8 *out)
+{
+ g_autoptr(GHmac) hmac = g_hmac_new (G_CHECKSUM_SHA256, key, key_len);
+ gsize digest_len = 32;
+
+ g_hmac_update (hmac, data, data_len);
+ g_hmac_get_digest (hmac, out, &digest_len);
+}
+
+/**
+ * goodix_crypto_aes_cbc_decrypt:
+ *
+ * AES-128-CBC decryption using OpenSSL EVP.
+ * No padding (input must be a multiple of 16 bytes).
+ * Returns TRUE only if the complete input was decrypted; discard out on failure.
+ */
+gboolean
+goodix_crypto_aes_cbc_decrypt (const guint8 *key,
+ const guint8 *iv,
+ const guint8 *in,
+ gsize in_len,
+ guint8 *out)
+{
+ EVP_CIPHER_CTX *ctx;
+ int out_len = 0, final_len = 0;
+ gboolean success;
+
+ if (in_len > G_MAXINT || in_len % 16 != 0)
+ return FALSE;
+
+ ctx = EVP_CIPHER_CTX_new ();
+ if (!ctx)
+ return FALSE;
+
+ success = EVP_DecryptInit_ex (ctx, EVP_aes_128_cbc (), NULL, key, iv) == 1 &&
+ EVP_CIPHER_CTX_set_padding (ctx, 0) == 1 &&
+ EVP_DecryptUpdate (ctx, out, &out_len, in, (int) in_len) == 1 &&
+ out_len >= 0 && (gsize) out_len <= in_len &&
+ EVP_DecryptFinal_ex (ctx, out + out_len, &final_len) == 1 &&
+ final_len >= 0 && (gsize) final_len == in_len - (gsize) out_len;
+ EVP_CIPHER_CTX_free (ctx);
+ return success;
+}
+
+/**
+ * goodix_crypto_derive_session_key:
+ *
+ * TLS 1.0-style PRF: HMAC-SHA256 based P_hash.
+ * seed = "master secret" + random_data
+ * A(0) = seed, A(i) = HMAC(psk, A(i-1))
+ * output = HMAC(psk, A(1)+seed) + HMAC(psk, A(2)+seed) + ...
+ */
+void
+goodix_crypto_derive_session_key (const guint8 *psk,
+ gsize psk_len,
+ const guint8 *random_data,
+ gsize random_len,
+ guint8 *out_key,
+ gsize key_len)
+{
+ const gchar *label = "master secret";
+ gsize label_len = strlen (label);
+ gsize seed_len = label_len + random_len;
+ g_autofree guint8 *seed = g_malloc (seed_len);
+ guint8 a_val[32]; /* A(i) */
+ guint8 hmac_out[32];
+ gsize offset = 0;
+
+ memcpy (seed, label, label_len);
+ memcpy (seed + label_len, random_data, random_len);
+
+ /* A(0) = seed; first iteration: A(1) = HMAC(psk, seed) */
+ goodix_crypto_hmac_sha256 (psk, psk_len, seed, seed_len, a_val);
+
+ while (offset < key_len)
+ {
+ /* HMAC(psk, A(i) + seed) */
+ gsize concat_len = 32 + seed_len;
+ g_autofree guint8 *concat = g_malloc (concat_len);
+
+ memcpy (concat, a_val, 32);
+ memcpy (concat + 32, seed, seed_len);
+ goodix_crypto_hmac_sha256 (psk, psk_len, concat, concat_len, hmac_out);
+
+ gsize copy_len = MIN (32, key_len - offset);
+ memcpy (out_key + offset, hmac_out, copy_len);
+ offset += copy_len;
+
+ /* A(i+1) = HMAC(psk, A(i)) */
+ goodix_crypto_hmac_sha256 (psk, psk_len, a_val, 32, a_val);
+ }
+}
+
+/**
+ * goodix_crypto_gea_decrypt:
+ *
+ * GEA stream cipher decryption (LFSR-based, ported from Python).
+ * key4 points to 4 bytes of key material.
+ * Processes data in 2-byte units (little-endian).
+ */
+void
+goodix_crypto_gea_decrypt (const guint8 *key4,
+ const guint8 *in,
+ gsize in_len,
+ guint8 *out)
+{
+ guint32 key = (guint32) key4[0] |
+ ((guint32) key4[1] << 8) |
+ ((guint32) key4[2] << 16) |
+ ((guint32) key4[3] << 24);
+ guint32 adjacent_key_xor, keystream_bits;
+ guint16 key_low_word, ciphertext_word, keystream_word;
+
+ for (gsize i = 0; i + 1 < in_len; i += 2)
+ {
+ adjacent_key_xor = (key >> 1 ^ key) & 0xFFFFFFFF;
+ keystream_bits = (((((((
+ ((key >> 0xF & 0x2000) | (key & 0x1000000)) >> 1 |
+ (key & 0x20000)) >>
+ 2 |
+ (key & 0x1000)) >>
+ 3 |
+ ((key >> 7 ^ key) & 0x80000)) >>
+ 1 |
+ ((key >> 0xF ^ key) & 0x4000)) >>
+ 2 |
+ (key & 0x2000)) >>
+ 2 |
+ (adjacent_key_xor & 0x40) | (key & 0x20)) >>
+ 1 |
+ ((key >> 9 ^ key << 8) & 0x800) |
+ ((key >> 0x14 ^ key * 2) & 4) |
+ ((key * 8 ^ key >> 0x10) & 0x4000) |
+ ((key >> 2 ^ key >> 0x10) & 0x80) |
+ ((key << 6 ^ key >> 7) & 0x100) |
+ ((key & 0x100) << 7));
+ keystream_bits = keystream_bits & 0xFFFFFFFF;
+ key_low_word = key & 0xFFFF;
+ key = ((key ^ (adjacent_key_xor >> 0x14 ^ key) >> 10) << 0x1F |
+ key >> 1) &
+ 0xFFFFFFFF;
+
+ ciphertext_word = (guint16) in[i] | ((guint16) in[i + 1] << 8);
+ keystream_word = (guint16) (((keystream_bits >> 8) & 0xFFFF) +
+ ((keystream_bits & 0xFF) | (key_low_word & 1)) * 0x100);
+ guint16 plaintext_word = ciphertext_word ^ keystream_word;
+ out[i] = plaintext_word & 0xFF;
+ out[i + 1] = (plaintext_word >> 8) & 0xFF;
+ }
+
+ if (in_len % 2 != 0)
+ out[in_len - 1] = in[in_len - 1];
+}
+
+/**
+ * goodix_crypto_gtls_init:
+ *
+ * Initialize GTLS context with PSK.
+ */
+void
+goodix_crypto_gtls_init (GoodixGtlsCtx *ctx,
+ const guint8 *psk)
+{
+ memset (ctx, 0, sizeof (GoodixGtlsCtx));
+ memcpy (ctx->psk, psk, GOODIX_PSK_LEN);
+ ctx->state = 0;
+}
+
+/**
+ * goodix_crypto_gtls_derive_keys:
+ *
+ * Given client_random and server_random are set, derive all session keys.
+ * Returns TRUE on success.
+ */
+gboolean
+goodix_crypto_gtls_derive_keys (GoodixGtlsCtx *ctx)
+{
+ guint8 random_data[64];
+ guint8 session_key[GOODIX_SESSION_KEY_LEN];
+
+ memcpy (random_data, ctx->client_random, 32);
+ memcpy (random_data + 32, ctx->server_random, 32);
+
+ goodix_crypto_derive_session_key (ctx->psk, GOODIX_PSK_LEN,
+ random_data, 64,
+ session_key, GOODIX_SESSION_KEY_LEN);
+
+ memcpy (ctx->symmetric_key, session_key, 16);
+ memcpy (ctx->symmetric_iv, session_key + 16, 16);
+ memcpy (ctx->hmac_key, session_key + 32, 32);
+ ctx->hmac_client_counter_init =
+ (guint16) session_key[64] | ((guint16) session_key[65] << 8);
+ ctx->hmac_server_counter_init =
+ (guint16) session_key[66] | ((guint16) session_key[67] << 8);
+
+ return TRUE;
+}
+
+/**
+ * goodix_crypto_gtls_verify_identity:
+ *
+ * Compute client identity and compare with server identity.
+ * client_identity = HMAC-SHA256(hmac_key, client_random + server_random)
+ * Returns TRUE if they match.
+ */
+gboolean
+goodix_crypto_gtls_verify_identity (GoodixGtlsCtx *ctx)
+{
+ guint8 random_data[64];
+
+ memcpy (random_data, ctx->client_random, 32);
+ memcpy (random_data + 32, ctx->server_random, 32);
+
+ goodix_crypto_hmac_sha256 (ctx->hmac_key, 32, random_data, 64,
+ ctx->client_identity);
+
+ return memcmp (ctx->client_identity, ctx->server_identity, 32) == 0;
+}
+
+/**
+ * goodix_crypto_gtls_decrypt_sensor_data:
+ *
+ * Decrypt sensor data received from the device.
+ * The encrypted message format:
+ * [data_type(4 LE)][msg_length(4 LE)][encrypted_payload][hmac(32)]
+ *
+ * The encrypted payload is processed in 15 blocks:
+ * - Even blocks (0,2,4,...,14): pass through (GEA encrypted)
+ * - Odd blocks (1,3,...,13): AES-CBC decrypt first
+ * Block sizes: block 0 = 0x3A7, blocks 1-13 = 0x3F0, block 14 = remainder
+ *
+ * After reassembly:
+ * 1. Verify HMAC over last 0x400 bytes and advance receive counter
+ * 2. Require an established session (state 5)
+ * 3. Strip first 5 bytes
+ * 4. Verify CRC32-MPEG2 over data (excl. last 4 bytes)
+ * 5. GEA decrypt using first 4 bytes of symmetric_key
+ *
+ * Returns newly allocated decrypted data, or NULL on error.
+ */
+guint8 *
+goodix_crypto_gtls_decrypt_sensor_data (GoodixGtlsCtx *ctx,
+ const guint8 *encrypted,
+ gsize encrypted_len,
+ gsize *out_len)
+{
+ guint32 data_type, msg_length;
+ const guint8 *encrypted_payload;
+ gsize encrypted_payload_len;
+ const guint8 *payload_hmac;
+ guint8 *gea_encrypted = NULL;
+ gsize gea_len = 0;
+ guint8 computed_hmac[32];
+ guint8 hmac_data_prefix[4];
+ guint32 msg_gea_crc, computed_crc;
+ guint8 *decrypted = NULL;
+
+ if (encrypted_len < 8 + 0x20)
+ {
+ fp_warn ("Encrypted data too short: %zu", encrypted_len);
+ return NULL;
+ }
+
+ data_type = encrypted[0] | ((guint32) encrypted[1] << 8) |
+ ((guint32) encrypted[2] << 16) | ((guint32) encrypted[3] << 24);
+
+ if (data_type != 0xAA01)
+ {
+ fp_warn ("Unexpected sensor data type: 0x%x", data_type);
+ return NULL;
+ }
+
+ msg_length = encrypted[4] | ((guint32) encrypted[5] << 8) |
+ ((guint32) encrypted[6] << 16) | ((guint32) encrypted[7] << 24);
+
+ if (msg_length != (guint32) encrypted_len)
+ {
+ fp_warn ("Sensor data length mismatch: %u != %zu",
+ msg_length, encrypted_len);
+ return NULL;
+ }
+
+ encrypted_payload = encrypted + 8;
+ encrypted_payload_len = encrypted_len - 8 - 0x20;
+ payload_hmac = encrypted + encrypted_len - 0x20;
+
+ /* Process 15 blocks: alternating passthrough/AES-CBC */
+ gea_encrypted = g_malloc (encrypted_payload_len);
+
+ const guint8 *ep = encrypted_payload;
+ gsize ep_remaining = encrypted_payload_len;
+
+ for (int block = 0; block < 15; block++)
+ {
+ gsize block_size;
+
+ if (block % 2 == 0)
+ {
+ /* Pass-through block */
+ if (block == 0)
+ block_size = MIN (0x3A7, ep_remaining);
+ else if (block == 14)
+ block_size = ep_remaining;
+ else
+ block_size = MIN (0x3F0, ep_remaining);
+
+ memcpy (gea_encrypted + gea_len, ep, block_size);
+ gea_len += block_size;
+ ep += block_size;
+ ep_remaining -= block_size;
+ }
+ else
+ {
+ /* AES-CBC decrypt block */
+ block_size = MIN (0x3F0, ep_remaining);
+
+ if (!goodix_crypto_aes_cbc_decrypt (ctx->symmetric_key,
+ ctx->symmetric_iv,
+ ep, block_size,
+ gea_encrypted + gea_len))
+ {
+ fp_warn ("AES-CBC sensor block decryption failed");
+ g_free (gea_encrypted);
+ return NULL;
+ }
+ gea_len += block_size;
+ ep += block_size;
+ ep_remaining -= block_size;
+ }
+ }
+
+ /* Verify HMAC over last 0x400 bytes of gea_encrypted */
+ hmac_data_prefix[0] = ctx->hmac_server_counter & 0xFF;
+ hmac_data_prefix[1] = (ctx->hmac_server_counter >> 8) & 0xFF;
+ hmac_data_prefix[2] = (ctx->hmac_server_counter >> 16) & 0xFF;
+ hmac_data_prefix[3] = (ctx->hmac_server_counter >> 24) & 0xFF;
+
+ {
+ gsize hmac_data_len = 4 + MIN (0x400, gea_len);
+ g_autofree guint8 *hmac_data_buf = g_malloc (hmac_data_len);
+
+ memcpy (hmac_data_buf, hmac_data_prefix, 4);
+ if (gea_len >= 0x400)
+ memcpy (hmac_data_buf + 4, gea_encrypted + gea_len - 0x400, 0x400);
+ else
+ memcpy (hmac_data_buf + 4, gea_encrypted, gea_len);
+
+ goodix_crypto_hmac_sha256 (ctx->hmac_key, 32,
+ hmac_data_buf, hmac_data_len,
+ computed_hmac);
+ }
+
+ if (memcmp (computed_hmac, payload_hmac, 32) != 0)
+ {
+ fp_warn ("HMAC verification failed");
+ g_free (gea_encrypted);
+ return NULL;
+ }
+
+ fp_dbg ("Encrypted payload HMAC verified");
+ ctx->hmac_server_counter = (ctx->hmac_server_counter + 1) & 0xFFFFFFFF;
+
+ /* Native 0x180024940 consumes the authenticated counter even when the
+ * handshake has not completed. Derived keys alone do not admit an image. */
+ if (ctx->state != 5)
+ {
+ fp_warn ("Sensor data received in incomplete GTLS state: %d", ctx->state);
+ g_free (gea_encrypted);
+ return NULL;
+ }
+
+ /* Strip first 5 bytes */
+ if (gea_len < 5 + 4)
+ {
+ fp_warn ("GEA payload too short: %zu", gea_len);
+ g_free (gea_encrypted);
+ return NULL;
+ }
+
+ guint8 *gea_data = gea_encrypted + 5;
+ gsize gea_data_len = gea_len - 5;
+
+ /* Extract and verify CRC */
+ msg_gea_crc = goodix_crypto_decode_u32 (gea_data + gea_data_len - 4);
+ gea_data_len -= 4;
+
+ if (gea_data_len % 2 != 0)
+ {
+ fp_warn ("GEA data length is odd: %zu", gea_data_len);
+ g_free (gea_encrypted);
+ return NULL;
+ }
+
+ computed_crc = goodix_crypto_crc32_mpeg2 (gea_data, gea_data_len);
+ if (computed_crc != msg_gea_crc)
+ {
+ fp_warn ("CRC check failed: computed 0x%08x, expected 0x%08x",
+ computed_crc, msg_gea_crc);
+ g_free (gea_encrypted);
+ return NULL;
+ }
+ fp_dbg ("GEA data CRC verified");
+
+ /* GEA decrypt */
+ decrypted = g_malloc (gea_data_len);
+ goodix_crypto_gea_decrypt (ctx->symmetric_key, gea_data, gea_data_len,
+ decrypted);
+
+ *out_len = gea_data_len;
+ g_free (gea_encrypted);
+ return decrypted;
+}
diff --git a/libfprint/drivers/goodix53x5/device/crypto.h b/libfprint/drivers/goodix53x5/device/crypto.h
new file mode 100644
index 0000000..3218439
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/crypto.h
@@ -0,0 +1,87 @@
+/*
+ * Goodix 53x5 driver for libfprint — Crypto layer
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#pragma once
+
+#include <glib.h>
+
+/* All-zero PSK (32 bytes) */
+#define GOODIX_PSK_LEN 32
+
+/* GTLS session key material size */
+#define GOODIX_SESSION_KEY_LEN 0x44
+
+/* --- GTLS context --- */
+typedef struct
+{
+ gint state;
+ guint8 client_random[32];
+ guint8 server_random[32];
+ guint8 client_identity[32];
+ guint8 server_identity[32];
+ guint8 symmetric_key[16];
+ guint8 symmetric_iv[16];
+ guint8 hmac_key[32];
+ guint16 hmac_client_counter_init;
+ guint16 hmac_server_counter_init;
+ guint32 hmac_client_counter;
+ guint32 hmac_server_counter;
+ guint8 psk[GOODIX_PSK_LEN];
+} GoodixGtlsCtx;
+
+void goodix_crypto_gtls_init (GoodixGtlsCtx *ctx,
+ const guint8 *psk);
+
+gboolean goodix_crypto_gtls_derive_keys (GoodixGtlsCtx *ctx);
+
+gboolean goodix_crypto_gtls_verify_identity (GoodixGtlsCtx *ctx);
+
+guint8 *goodix_crypto_gtls_decrypt_sensor_data (GoodixGtlsCtx *ctx,
+ const guint8 *encrypted,
+ gsize encrypted_len,
+ gsize *out_len);
+
+void goodix_crypto_derive_session_key (const guint8 *psk,
+ gsize psk_len,
+ const guint8 *random_data,
+ gsize random_len,
+ guint8 *out_key,
+ gsize key_len);
+
+void goodix_crypto_gea_decrypt (const guint8 *key4,
+ const guint8 *in,
+ gsize in_len,
+ guint8 *out);
+
+guint32 goodix_crypto_crc32_mpeg2 (const guint8 *data,
+ gsize len);
+
+guint32 goodix_crypto_decode_u32 (const guint8 *data);
+
+gboolean goodix_crypto_aes_cbc_decrypt (const guint8 *key,
+ const guint8 *iv,
+ const guint8 *in,
+ gsize in_len,
+ guint8 *out);
+
+void goodix_crypto_hmac_sha256 (const guint8 *key,
+ gsize key_len,
+ const guint8 *data,
+ gsize data_len,
+ guint8 *out);
diff --git a/libfprint/drivers/goodix53x5/device/debug.h b/libfprint/drivers/goodix53x5/device/debug.h
new file mode 100644
index 0000000..94e89db
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/debug.h
@@ -0,0 +1,131 @@
+/*
+ * Goodix 53x5 driver for libfprint - opt-in diagnostic instrumentation
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include "fpi-device.h"
+#include "goodix53x5.h"
+
+typedef struct _GoodixMilanRuntimeOutput GoodixMilanRuntimeOutput;
+
+#ifdef GOODIX53X5_DEBUG
+
+/* The diagnostic build recognizes these independent controls:
+ * GOODIX53X5_DUMP_DIR, GOODIX53X5_DUMP_PROBES, GOODIX53X5_DUMP_TEMPLATES,
+ * GOODIX53X5_LOG_TIMING, and GOODIX53X5_LOG_DIAGNOSTICS. */
+#define GOODIX53X5_DEBUG_ONLY(...) __VA_ARGS__
+
+typedef struct
+{
+ FpiDeviceAction action;
+ guint64 generation_use_index;
+ gboolean setup_initialized;
+ gboolean setup_refresh_pending;
+ gboolean setup_not_ready;
+ GBytes *setup_tx_on;
+ GBytes *live_raw;
+} GoodixDebugRuntimeMetadata;
+
+typedef struct
+{
+ gint64 action_started_us;
+ gint64 open_started_us;
+ gint64 open_phase_started_us;
+ const gchar *open_last_state_name;
+ gint64 finger_wait_started_us;
+ gint64 finger_wait_phase_started_us;
+ guint finger_wait_false_event_retries;
+ gint64 finger_up_started_us;
+ gint64 finger_up_phase_started_us;
+ gint64 ref_capture_started_us;
+ gint64 ref_capture_phase_started_us;
+ gint64 capture_started_us;
+ gint64 capture_phase_started_us;
+ gint64 deactivate_started_us;
+ gint64 deactivate_phase_started_us;
+} GoodixDebugTiming;
+
+gboolean goodix_debug_dump_enabled (void);
+void goodix_debug_dump_image (const gchar *prefix,
+ const guint8 *img,
+ gsize len);
+void goodix_debug_dump_raw12 (const gchar *prefix,
+ const guint16 *img,
+ gsize len);
+void goodix_debug_dump_pair (const gchar *prefix,
+ const guint16 *raw_img,
+ const guint8 *img);
+void goodix_debug_dump_probe (FpiDeviceAction action,
+ const gchar *outcome,
+ const guint16 *raw_img,
+ const guint8 *img);
+
+gboolean goodix_debug_timing_enabled (void);
+const gchar *goodix_debug_runtime_status_name (guint status);
+const gchar *goodix_debug_study_action_name (guint action);
+gchar *goodix_debug_format_winner (guint index, gsize position);
+gchar *goodix_debug_format_template_features (
+ const GoodixMilanRuntimeOutput *output);
+void goodix_debug_timing_log (FpDevice *dev,
+ const gchar *scope,
+ const gchar *event,
+ gint64 duration_us,
+ const gchar *detail);
+void goodix_debug_timing_action_start (FpiDeviceGoodix53x5 *self,
+ FpDevice *dev,
+ const gchar *detail);
+void goodix_debug_timing_action_done (FpiDeviceGoodix53x5 *self,
+ FpDevice *dev,
+ const gchar *detail);
+void goodix_debug_timing_open_state (FpiDeviceGoodix53x5 *self,
+ FpDevice *dev,
+ const gchar *state_name,
+ gint64 now_us);
+void goodix_debug_timing_open_done (FpiDeviceGoodix53x5 *self,
+ FpDevice *dev,
+ const gchar *detail);
+
+void goodix_debug_capture_runtime_metadata (
+ GoodixDebugRuntimeMetadata *metadata,
+ FpiDeviceAction action,
+ const guint16 *setup_tx_on,
+ const guint16 *live_raw,
+ guint64 generation_use_index,
+ gboolean setup_initialized,
+ gboolean setup_refresh_pending,
+ gboolean setup_not_ready);
+void goodix_debug_clear_runtime_metadata (
+ GoodixDebugRuntimeMetadata *metadata);
+void goodix_debug_log_runtime_result (
+ FpDevice *dev,
+ guint stage,
+ const GoodixDebugRuntimeMetadata *metadata,
+ const GoodixMilanRuntimeOutput *output,
+ gboolean driver_cancellation_observed);
+
+#else
+
+#define GOODIX53X5_DEBUG_ONLY(...)
+
+#define goodix_debug_dump_enabled() FALSE
+#define goodix_debug_timing_enabled() FALSE
+#define goodix_debug_dump_image(...) G_STMT_START { } G_STMT_END
+#define goodix_debug_dump_raw12(...) G_STMT_START { } G_STMT_END
+#define goodix_debug_dump_pair(...) G_STMT_START { } G_STMT_END
+#define goodix_debug_dump_probe(...) G_STMT_START { } G_STMT_END
+#define goodix_debug_timing_log(...) G_STMT_START { } G_STMT_END
+#define goodix_debug_timing_action_start(...) G_STMT_START { } G_STMT_END
+#define goodix_debug_timing_action_done(...) G_STMT_START { } G_STMT_END
+#define goodix_debug_timing_open_state(...) G_STMT_START { } G_STMT_END
+#define goodix_debug_timing_open_done(...) G_STMT_START { } G_STMT_END
+#define goodix_debug_clear_runtime_metadata(...) G_STMT_START { } G_STMT_END
+#define goodix_debug_log_runtime_result(...) G_STMT_START { } G_STMT_END
+
+#endif
diff --git a/libfprint/drivers/goodix53x5/device/enroll.c b/libfprint/drivers/goodix53x5/device/enroll.c
new file mode 100644
index 0000000..f1e0de4
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/enroll.c
@@ -0,0 +1,578 @@
+/*
+ * Goodix 53x5 driver for libfprint - native Milan enrollment flow
+ * Copyright (C) 2024-2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "fpi-print.h"
+#include "device/enroll.h"
+#include "milan/match/match.h"
+#include "milan/print.h"
+#include "driver-private.h"
+#include "milan/runtime.h"
+#include "device/persistence.h"
+#include "device/scan.h"
+#include "device/session.h"
+
+typedef enum {
+ GOODIX_ENROLL_REINIT = 0,
+ GOODIX_ENROLL_REINIT_DONE,
+ GOODIX_ENROLL_SCAN,
+ GOODIX_ENROLL_FINISH,
+ GOODIX_ENROLL_NUM_STATES,
+} GoodixEnrollState;
+
+typedef struct
+{
+ GoodixMilanRuntimeInput *runtime_input;
+ guint64 action_epoch;
+ guint64 generation_id;
+ guint stage;
+ GOODIX53X5_DEBUG_ONLY (GoodixDebugRuntimeMetadata debug_metadata;
+ )
+} GoodixEnrollTaskData;
+
+#ifdef GOODIX53X5_DEBUG
+static void
+goodix_enroll_log_runtime_result (FpDevice *dev,
+ GoodixEnrollTaskData *data,
+ const GoodixMilanRuntimeOutput *output,
+ gboolean driver_cancellation_observed)
+{
+ goodix_debug_log_runtime_result (dev, data->stage + 1,
+ &data->debug_metadata, output,
+ driver_cancellation_observed);
+}
+#else
+#define goodix_enroll_log_runtime_result(...) G_STMT_START { } G_STMT_END
+#endif
+
+static void
+goodix_enroll_task_data_free (GoodixEnrollTaskData *data)
+{
+ if (!data)
+ return;
+ goodix_milan_runtime_input_free (data->runtime_input);
+ GOODIX53X5_DEBUG_ONLY (
+ goodix_debug_clear_runtime_metadata (&data->debug_metadata);
+ )
+ g_free (data);
+}
+
+static gboolean
+goodix_enroll_runtime_cancelled (GoodixMilanRuntimeCheckpoint checkpoint,
+ gsize gallery_position,
+ gpointer user_data)
+{
+ (void) checkpoint;
+ (void) gallery_position;
+ return g_cancellable_is_cancelled (G_CANCELLABLE (user_data));
+}
+
+static void
+goodix_enroll_worker (GTask *task,
+ gpointer source_object,
+ gpointer task_data,
+ GCancellable *cancellable)
+{
+ GoodixEnrollTaskData *data = task_data;
+
+ (void) source_object;
+ (void) cancellable;
+ g_task_return_pointer (
+ task, goodix_milan_runtime_run (data->runtime_input),
+ (GDestroyNotify) goodix_milan_runtime_output_free);
+}
+
+#ifdef GOODIX53X5_DEBUG
+static void
+goodix_enroll_set_processed_image (FpiDeviceGoodix53x5 *self,
+ GoodixMilanRuntimeOutput *output)
+{
+ const guint8 *image;
+ gsize size;
+
+ g_clear_pointer (&self->captured_image, g_free);
+ image = output->processed_image ?
+ g_bytes_get_data (output->processed_image, &size) : NULL;
+ if (image && size == GOODIX_SENSOR_PIXELS)
+ self->captured_image = g_memdup2 (image, size);
+}
+#endif
+
+static void
+goodix_enroll_task_done (GObject *source_object,
+ GAsyncResult *result,
+ gpointer user_data)
+{
+ FpDevice *dev = FP_DEVICE (source_object);
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixEnrollTaskData *data = g_task_get_task_data (G_TASK (result));
+
+ g_autoptr(GError) task_error = NULL;
+ GoodixMilanRuntimeOutput *output = g_task_propagate_pointer (
+ G_TASK (result), &task_error);
+ gboolean task_owned;
+ gboolean same_action;
+ gboolean action_owned;
+ gboolean generation_current;
+ gboolean cancelled;
+ gboolean enrollment_admitted;
+ GoodixMilanEnrollmentAttemptStatus enrollment_status =
+ GOODIX_MILAN_ENROLLMENT_RETRY_REMOVE;
+ GoodixMilanEnrollmentResult enrollment_result = { 0 };
+
+ (void) user_data;
+ task_owned = self->milan_task == G_TASK (result);
+ same_action = task_owned &&
+ fpi_device_get_current_action (dev) == FPI_DEVICE_ACTION_ENROLL &&
+ self->enroll_stage == (gint) data->stage;
+ cancelled = same_action &&
+ (fpi_device_action_is_cancelled (dev) ||
+ !self->cancel || g_cancellable_is_cancelled (self->cancel) ||
+ (output && output->status == GOODIX_MILAN_RUNTIME_CANCELLED) ||
+ (task_error && g_error_matches (task_error, G_IO_ERROR,
+ G_IO_ERROR_CANCELLED)));
+ action_owned = same_action &&
+ (self->action_epoch == data->action_epoch || cancelled);
+ generation_current = action_owned && self->milan_generation &&
+ self->milan_generation->generation_id ==
+ data->generation_id;
+ if (task_owned)
+ g_clear_object (&self->milan_task);
+
+ if (!action_owned)
+ {
+ if (output)
+ goodix_enroll_log_runtime_result (dev, data, output, FALSE);
+ goodix_milan_runtime_output_free (output);
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ if (task_owned && self->profile9_fdt.owner)
+ goodix_scan_set_disposition (dev, GOODIX_SCAN_DISPOSITION_CANCELLED,
+ NULL);
+ return;
+ }
+
+ if (generation_current && output &&
+ output->action_epoch == data->action_epoch &&
+ output->generation_id == data->generation_id &&
+ output->preprocess_state_valid && !cancelled)
+ {
+ self->milan_generation->state = output->preprocess_state;
+ self->milan_generation->profile_state = output->profile_state;
+ }
+ else if (generation_current && output &&
+ output->action_epoch == data->action_epoch &&
+ output->generation_id == data->generation_id &&
+ output->setup_state_valid)
+ {
+ self->milan_generation->profile_state.setup_initialized =
+ output->profile_state.setup_initialized;
+ self->milan_generation->profile_state.setup_refresh_pending =
+ output->profile_state.setup_refresh_pending;
+ self->milan_generation->profile_state.setup_not_ready =
+ output->profile_state.setup_not_ready;
+ }
+
+ if (cancelled)
+ {
+ if (output)
+ goodix_enroll_log_runtime_result (dev, data, output, TRUE);
+ goodix_milan_runtime_output_free (output);
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ goodix_scan_set_disposition (dev, GOODIX_SCAN_DISPOSITION_CANCELLED,
+ NULL);
+ return;
+ }
+
+ if (!output || task_error ||
+ output->action_epoch != data->action_epoch ||
+ output->generation_id != data->generation_id)
+ {
+ goodix_milan_runtime_output_free (output);
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_FATAL,
+ task_error ? g_steal_pointer (&task_error) :
+ fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_GENERAL,
+ "Native Milan enrollment task returned invalid output"));
+ return;
+ }
+
+ GOODIX53X5_DEBUG_ONLY (goodix_enroll_set_processed_image (self, output);
+ )
+ enrollment_admitted = goodix_milan_runtime_enrollment_admitted (output);
+ /* Native non-policy merge failures break an unsaturated rollback streak,
+ * including extraction that succeeds with no records to insert. Sample
+ * quality/preprocessing rejection never enters that merge boundary. */
+ if (output->enrollment_sample_admitted && !enrollment_admitted &&
+ self->enroll_bad_continue_count < 3)
+ self->enroll_bad_continue_count = 0;
+
+ if (enrollment_admitted)
+ {
+ enrollment_status = goodix_milan_enrollment_transaction_attempt (
+ &self->enroll_transaction, output->probe_template,
+ &self->enroll_bad_record_count, &self->enroll_bad_continue_count,
+ &enrollment_result);
+ if (enrollment_status == GOODIX_MILAN_ENROLLMENT_RETRY_REMOVE)
+ fp_dbg ("Native Milan enrollment retry stage %u: relation/combine "
+ "failed",
+ data->stage + 1);
+ }
+
+ if (enrollment_admitted &&
+ enrollment_status == GOODIX_MILAN_ENROLLMENT_ACCEPTED)
+ {
+ GOODIX53X5_DEBUG_ONLY (
+ g_autofree gchar * prefix = g_strdup_printf (
+ "enroll-stage-%u", data->stage + 1);
+
+ goodix_debug_dump_pair (prefix, self->captured_raw_image,
+ self->captured_image);
+ )
+ self->enroll_stage = (gint) goodix_milan_enrollment_transaction_count (
+ self->enroll_transaction);
+ g_clear_pointer (&self->pending_persistence_state, g_free);
+ /* Only final publication consumes this snapshot; every attempt already
+ * installed its valid preprocessing mutations into the live generation. */
+ if (self->enroll_stage == GOODIX_ENROLL_SAMPLES &&
+ output->preprocess_state_valid)
+ self->pending_persistence_state = g_memdup2 (
+ &output->preprocess_state, sizeof (output->preprocess_state));
+ GOODIX53X5_DEBUG_ONLY (
+ fp_dbg ("Native Milan enrollment stage %d/%d quality=%d coverage=%d "
+ "records=%u partitions=%u/%u",
+ self->enroll_stage, GOODIX_ENROLL_SAMPLES, output->quality,
+ output->coverage, output->probe_record_count,
+ output->probe_partition0_count,
+ output->probe_partition1_count);
+ )
+ self->pending_enroll_progress = TRUE;
+ self->pending_enroll_stage = self->enroll_stage;
+ g_clear_error (&self->pending_enroll_error);
+ }
+ else if (enrollment_admitted &&
+ enrollment_status == GOODIX_MILAN_ENROLLMENT_RETRY_CENTER)
+ {
+ GOODIX53X5_DEBUG_ONLY (
+ fp_dbg ("Native Milan enrollment rollback stage %u: overlap=%d/%d "
+ "detail=%u",
+ data->stage + 1, enrollment_result.previous_overlap,
+ enrollment_result.overlap, enrollment_result.reject_detail);
+ )
+ self->pending_enroll_progress = TRUE;
+ self->pending_enroll_stage = self->enroll_stage;
+ g_clear_error (&self->pending_enroll_error);
+ self->pending_enroll_error =
+ fpi_device_retry_new (FP_DEVICE_RETRY_CENTER_FINGER);
+ }
+ else if (enrollment_admitted &&
+ enrollment_status == GOODIX_MILAN_ENROLLMENT_RETRY_REMOVE)
+ {
+ GOODIX53X5_DEBUG_ONLY (
+ g_autofree gchar * prefix = g_strdup_printf (
+ "enroll-retry-stage-%u-relation-combine", data->stage + 1);
+
+ goodix_debug_dump_pair (prefix, self->captured_raw_image,
+ self->captured_image);
+ )
+ self->pending_enroll_progress = TRUE;
+ self->pending_enroll_stage = self->enroll_stage;
+ g_clear_error (&self->pending_enroll_error);
+ self->pending_enroll_error =
+ fpi_device_retry_new (FP_DEVICE_RETRY_REMOVE_FINGER);
+ }
+ else if (output->status == GOODIX_MILAN_RUNTIME_RETRY ||
+ output->preprocess_state_valid)
+ {
+ GOODIX53X5_DEBUG_ONLY (
+ const gchar * reason = output->status == GOODIX_MILAN_RUNTIME_RETRY ?
+ "extract" : "quality";
+ g_autofree gchar *prefix = g_strdup_printf (
+ "enroll-retry-stage-%u-%s", data->stage + 1, reason);
+
+ goodix_debug_dump_pair (prefix, self->captured_raw_image,
+ self->captured_image);
+ )
+ self->pending_enroll_progress = TRUE;
+ self->pending_enroll_stage = self->enroll_stage;
+ g_clear_error (&self->pending_enroll_error);
+ self->pending_enroll_error = fpi_device_retry_new (
+ output->coverage < GOODIX_MILAN_ENROLL_MIN_COVERAGE ?
+ FP_DEVICE_RETRY_CENTER_FINGER : FP_DEVICE_RETRY_REMOVE_FINGER);
+ }
+ else
+ {
+ GError *error = fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_GENERAL, "Native Milan enrollment extraction failed");
+
+ goodix_enroll_log_runtime_result (dev, data, output, FALSE);
+ goodix_milan_runtime_output_free (output);
+#ifdef GOODIX53X5_DEBUG
+ g_clear_pointer (&self->captured_image, g_free);
+#endif
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ goodix_scan_set_disposition (dev, GOODIX_SCAN_DISPOSITION_FATAL, error);
+ return;
+ }
+
+ goodix_enroll_log_runtime_result (dev, data, output, FALSE);
+ goodix_milan_runtime_output_free (output);
+#ifdef GOODIX53X5_DEBUG
+ g_clear_pointer (&self->captured_image, g_free);
+#endif
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ goodix_scan_set_disposition (
+ dev,
+ self->enroll_stage >= GOODIX_ENROLL_SAMPLES ?
+ GOODIX_SCAN_DISPOSITION_ENROLL_FINAL_AFTER_UP :
+ GOODIX_SCAN_DISPOSITION_ENROLL_CONTINUE_AFTER_UP,
+ NULL);
+}
+
+static void
+goodix_enroll_start_task (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixEnrollTaskData *data = g_new0 (GoodixEnrollTaskData, 1);
+
+ g_autoptr(GTask) task = NULL;
+
+ if (!self->milan_generation || !self->captured_raw_image || self->milan_task)
+ {
+ g_free (data);
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_FATAL,
+ fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_GENERAL,
+ "Native Milan enrollment input is missing or busy"));
+ return;
+ }
+ data->action_epoch = self->action_epoch;
+ data->generation_id = self->milan_generation->generation_id;
+ data->stage = self->enroll_stage;
+ GOODIX53X5_DEBUG_ONLY (
+ goodix_debug_capture_runtime_metadata (
+ &data->debug_metadata, FPI_DEVICE_ACTION_ENROLL,
+ self->milan_generation->setup_tx_on, self->captured_raw_image,
+ self->milan_generation->use_count,
+ self->milan_generation->profile_state.setup_initialized,
+ self->milan_generation->profile_state.setup_refresh_pending,
+ self->milan_generation->profile_state.setup_not_ready);
+ )
+ data->runtime_input = goodix_milan_runtime_input_new (
+ data->action_epoch, data->generation_id, GOODIX_MILAN_PURPOSE_ENROLL,
+ &self->milan_generation->state,
+ &self->milan_generation->profile_state,
+ self->milan_generation->setup_tx_on,
+ self->captured_raw_image, self->calib.tcode, self->calib.dac_h,
+ self->calib.dac_l, self->milan_sensor_subtype, NULL, 0);
+ if (!data->runtime_input)
+ {
+ goodix_enroll_task_data_free (data);
+ goodix_scan_set_disposition (
+ dev, GOODIX_SCAN_DISPOSITION_FATAL,
+ fpi_device_error_new (FP_DEVICE_ERROR_GENERAL));
+ return;
+ }
+ goodix_milan_persistence_bind_setup (data->runtime_input,
+ self->milan_generation);
+ goodix_milan_runtime_input_set_capture_health (data->runtime_input,
+ self->captured_enroll_allowed);
+ goodix_milan_runtime_input_set_cancel_check (
+ data->runtime_input, goodix_enroll_runtime_cancelled,
+ g_object_ref (self->cancel), g_object_unref);
+ task = g_task_new (dev, self->cancel, goodix_enroll_task_done, NULL);
+ g_task_set_check_cancellable (task, FALSE);
+ g_task_set_task_data (task, data,
+ (GDestroyNotify) goodix_enroll_task_data_free);
+ self->milan_task = g_object_ref (task);
+ g_task_run_in_thread (task, goodix_enroll_worker);
+}
+
+static void
+goodix_enroll_capture_ready (FpDevice *dev,
+ gpointer user_data)
+{
+ (void) user_data;
+ goodix_enroll_start_task (dev);
+}
+
+static void
+goodix_enroll_cycle_settled (FpDevice *dev,
+ GoodixScanDisposition disposition,
+ gpointer user_data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ (void) disposition;
+ (void) user_data;
+ if (!self->pending_enroll_progress)
+ return;
+
+ self->pending_enroll_progress = FALSE;
+ fpi_device_enroll_progress (dev, self->pending_enroll_stage, NULL,
+ g_steal_pointer (&self->pending_enroll_error));
+}
+
+static void
+goodix_enroll_ssm_handler (FpiSsm *ssm,
+ FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ switch (fpi_ssm_get_cur_state (ssm))
+ {
+ case GOODIX_ENROLL_REINIT:
+ if (!goodix_maybe_start_reinit_subsm (ssm, dev))
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_ENROLL_REINIT_DONE:
+ goodix_debug_timing_open_done (self, dev, "reinit");
+ self->needs_reinit = FALSE;
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_ENROLL_SCAN:
+ goodix_scan_start_coordinator_subsm (
+ ssm, dev, goodix_enroll_capture_ready,
+ goodix_enroll_cycle_settled, NULL);
+ break;
+
+ case GOODIX_ENROLL_FINISH:
+ fpi_ssm_mark_completed (ssm);
+ break;
+
+ case GOODIX_ENROLL_NUM_STATES:
+ g_assert_not_reached ();
+ }
+}
+
+static void
+goodix_enroll_complete (FpDevice *dev,
+ GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ FpPrint *print = NULL;
+
+ g_autoptr(GBytes) combined = NULL;
+ g_autoptr(GVariant) data = NULL;
+
+#ifdef GOODIX53X5_DEBUG
+ g_clear_pointer (&self->captured_image, g_free);
+#endif
+ g_clear_pointer (&self->captured_raw_image, g_free);
+
+ if (error)
+ {
+ if (goodix_error_indicates_stale_device (error))
+ self->needs_reinit = TRUE;
+ self->pending_enroll_progress = FALSE;
+ g_clear_error (&self->pending_enroll_error);
+ g_clear_pointer (&self->enroll_transaction,
+ goodix_milan_enrollment_transaction_free);
+ g_clear_pointer (&self->pending_persistence_state, g_free);
+ goodix_debug_timing_action_done (self, dev, error->message);
+ fpi_device_enroll_complete (dev, NULL, error);
+ return;
+ }
+
+ if (self->enroll_stage != GOODIX_ENROLL_SAMPLES ||
+ !self->enroll_transaction ||
+ goodix_milan_enrollment_transaction_count (
+ self->enroll_transaction) != GOODIX_ENROLL_SAMPLES ||
+ !self->pending_persistence_state)
+ {
+ GError *chronology_error = fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_GENERAL,
+ "Native Milan enrollment action state is incomplete");
+
+ g_clear_pointer (&self->enroll_transaction,
+ goodix_milan_enrollment_transaction_free);
+ g_clear_pointer (&self->pending_persistence_state, g_free);
+ fpi_device_enroll_complete (dev, NULL, chronology_error);
+ return;
+ }
+
+ combined = goodix_milan_enrollment_transaction_publish (
+ self->enroll_transaction);
+ if (combined)
+ data = goodix_milan_print_build_data (combined, &error);
+ if (!combined || !data)
+ {
+ g_clear_pointer (&self->enroll_transaction,
+ goodix_milan_enrollment_transaction_free);
+ g_clear_pointer (&self->pending_persistence_state, g_free);
+ if (!error)
+ error = fpi_device_error_new_msg (FP_DEVICE_ERROR_GENERAL,
+ "Failed to build native Milan template");
+ fpi_device_enroll_complete (dev, NULL, error);
+ return;
+ }
+
+ fpi_device_get_enroll_data (dev, &print);
+ fpi_print_set_type (print, FPI_PRINT_RAW);
+ g_object_set (print, "fpi-data", data, NULL);
+ g_clear_pointer (&self->enroll_transaction,
+ goodix_milan_enrollment_transaction_free);
+ fp_info ("Native Milan enrollment complete with %d stages",
+ GOODIX_ENROLL_SAMPLES);
+ goodix_milan_persistence_save (dev, self->pending_persistence_state);
+ g_clear_pointer (&self->pending_persistence_state, g_free);
+ goodix_debug_timing_action_done (self, dev, NULL);
+ fpi_device_enroll_complete (dev, g_object_ref (print), NULL);
+}
+
+static void
+goodix_enroll_ssm_done (FpiSsm *ssm, FpDevice *dev, GError *error)
+{
+ goodix_session_action_done (dev, error, goodix_enroll_complete);
+}
+
+void
+goodix_enroll_start (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ FpiSsm *ssm;
+
+ g_clear_object (&self->cancel);
+ self->cancel = g_cancellable_new ();
+ self->action_epoch++;
+ if (self->action_epoch == 0)
+ self->action_epoch++;
+ self->enroll_stage = 0;
+ g_clear_pointer (&self->enroll_transaction,
+ goodix_milan_enrollment_transaction_free);
+ self->enroll_transaction = goodix_milan_enrollment_transaction_new ();
+ self->enroll_bad_record_count = 0;
+ self->enroll_bad_continue_count = 0;
+ self->pending_enroll_progress = FALSE;
+ self->pending_enroll_stage = 0;
+ g_clear_error (&self->pending_enroll_error);
+#ifdef GOODIX53X5_DEBUG
+ g_clear_pointer (&self->captured_image, g_free);
+#endif
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ g_clear_pointer (&self->pending_persistence_state, g_free);
+ if (!self->enroll_transaction)
+ {
+ goodix_session_action_done (
+ dev, fpi_device_error_new (FP_DEVICE_ERROR_GENERAL), goodix_enroll_complete);
+ return;
+ }
+ goodix_debug_timing_action_start (self, dev, NULL);
+
+ ssm = fpi_ssm_new (dev, goodix_enroll_ssm_handler,
+ GOODIX_ENROLL_NUM_STATES);
+ fpi_ssm_start (ssm, goodix_enroll_ssm_done);
+}
diff --git a/libfprint/drivers/goodix53x5/device/enroll.h b/libfprint/drivers/goodix53x5/device/enroll.h
new file mode 100644
index 0000000..03e1d69
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/enroll.h
@@ -0,0 +1,26 @@
+/*
+ * Goodix 53x5 driver for libfprint — Enrollment flow
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#pragma once
+
+#include "driver-private.h"
+
+/* Reset enrollment action state and run the full enroll flow; reports
+ * completion through fpi_device_enroll_*. Implements FpDeviceClass::enroll. */
+void goodix_enroll_start (FpDevice *dev);
diff --git a/libfprint/drivers/goodix53x5/device/health.c b/libfprint/drivers/goodix53x5/device/health.c
new file mode 100644
index 0000000..4183a73
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/health.c
@@ -0,0 +1,419 @@
+/*
+ * Goodix 53x5 driver for libfprint - profile-9 sensor health
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ * SPDX-License-Identifier: LGPL-2.1-or-later
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/commands.h"
+#include "device/health.h"
+#include "device/transport.h"
+
+#include <float.h>
+#include <math.h>
+#include <openssl/rand.h>
+#include <string.h>
+
+#define GOODIX_HEALTH_ENROLL_THRESHOLD 600
+#define GOODIX_HEALTH_STUDY_THRESHOLD 300
+#define GOODIX_HEALTH_TOLERANCE 200
+#define GOODIX_HEALTH_INTERIOR ((GOODIX_SENSOR_WIDTH - 2) * (GOODIX_SENSOR_HEIGHT - 2))
+
+/* usbinterface!0615d0/0615d4: neither health init nor destroy clears these.
+ * Serialize module owners when different device contexts run concurrently. */
+static GMutex goodix_health_lock;
+static guint16 goodix_health_estimate;
+static guint16 goodix_health_enroll_checks;
+
+static guint16
+goodix_health_difference (guint16 first, guint16 second)
+{
+ guint16 difference = first - second;
+
+ return (gint16) difference > 0 ? difference : (guint16) (second - first);
+}
+
+/* usbinterface!013578: strict 800/1200 window for the mean, inclusive
+ * mean +/- tolerance window for the subsequent broken-pixel count. */
+static guint16
+goodix_health_measure (const guint16 *first, const guint16 *second)
+{
+ guint32 sum = 0;
+ guint16 count = 0;
+ guint16 broken = 0;
+ guint16 low, high;
+
+ for (guint row = 1; row < GOODIX_SENSOR_HEIGHT - 1; row++)
+ for (guint col = 1; col < GOODIX_SENSOR_WIDTH - 1; col++)
+ {
+ guint i = row * GOODIX_SENSOR_WIDTH + col;
+ guint16 difference = goodix_health_difference (first[i], second[i]);
+
+ if (difference > 800 && difference < 1200)
+ {
+ sum += difference;
+ count++;
+ }
+ }
+ if (!count)
+ return GOODIX_HEALTH_INTERIOR;
+
+ low = sum / count - GOODIX_HEALTH_TOLERANCE;
+ high = sum / count + GOODIX_HEALTH_TOLERANCE;
+ for (guint row = 1; row < GOODIX_SENSOR_HEIGHT - 1; row++)
+ for (guint col = 1; col < GOODIX_SENSOR_WIDTH - 1; col++)
+ {
+ guint i = row * GOODIX_SENSOR_WIDTH + col;
+ guint16 difference = goodix_health_difference (first[i], second[i]);
+
+ broken += difference < low || difference > high;
+ }
+ return broken;
+}
+
+/* usbinterface!0137cc calls this a mean-square error, but returns its rounded
+ * square root. Mean rounding precedes squared distances; the native square is
+ * signed 32-bit after multiplication. The length-zero masked-x86 path returns
+ * mean zero/root zero, reached when the enrollment counter wraps. */
+static gint16
+goodix_health_statistic (const guint16 *history, guint length, guint16 *mean)
+{
+ double sum = 0.0;
+ double variance = 0.0;
+ double root = 0.0;
+
+ if (!length)
+ {
+ *mean = 0;
+ return 0;
+ }
+ for (guint i = 0; i < length; i++)
+ sum += history[i];
+ *mean = (guint16) (sum / length + 0.5);
+ for (guint i = 0; i < length; i++)
+ {
+ gint32 delta = ABS ((gint32) history[i] - *mean);
+ gint32 square = (gint32) ((guint32) delta * (guint32) delta);
+
+ variance += square;
+ }
+ variance /= length;
+ if (variance > 0.0)
+ {
+ double previous = variance;
+
+ do
+ {
+ root = (previous + variance / previous) * 0.5;
+ if (fabs (previous - root) <= FLT_MIN)
+ break;
+ previous = root;
+ }
+ while (TRUE);
+ }
+ return (gint16) (gint32) (root + 0.5);
+}
+
+/* usbinterface!0138bc: estimate OLD history, first greatest cluster wins. */
+static guint16
+goodix_health_lookup (const guint16 history[30], guint16 previous)
+{
+ guint16 mean;
+ gint16 statistic = goodix_health_statistic (history, 8, &mean);
+ guint16 counts[30] = { 0 };
+ guint32 sums[30] = { 0 };
+ guint best = 0;
+
+ if (history[0] == history[1] && history[1] == history[2] &&
+ history[2] == history[3])
+ return history[0];
+ if (statistic < 5 && statistic != -1)
+ return mean;
+ for (guint i = 0; i < 30; i++)
+ {
+ for (guint j = 0; j < 30; j++)
+ if (ABS ((gint32) history[i] - history[j]) < 5)
+ {
+ counts[i]++;
+ sums[i] += history[j];
+ }
+ if (counts[i] > counts[best])
+ best = i;
+ }
+ mean = sums[best] / counts[best];
+ return counts[best] >= 10 && (guint32) previous >= mean + 600u ? mean : previous;
+}
+
+/* usbinterface!013b1c changes only the inserted value, never measured c. */
+static void
+goodix_health_insert (guint16 history[30], guint16 measured)
+{
+ guint16 limit = (guint16) (GOODIX_HEALTH_INTERIOR * 0.9);
+
+ if (measured > limit)
+ {
+ guint8 random[2] = { 0 };
+ guint16 word;
+
+ /* Native initializes the destination and ignores generate_random's
+ * result. Unlike handshake entropy this does not establish a key. */
+ (void) RAND_bytes (random, sizeof (random));
+ word = random[0] | ((guint16) random[1] << 8);
+ measured = 601 + word % (limit - 600);
+ }
+ memmove (history + 1, history, 29 * sizeof (*history));
+ history[0] = measured;
+}
+
+static void
+goodix_health_evaluate (GoodixSensorHealth *health, guint32 operation,
+ guint16 measured)
+{
+ guint16 estimate, difference;
+
+ g_mutex_lock (&goodix_health_lock);
+ estimate = goodix_health_lookup (health->history, goodix_health_estimate);
+ goodix_health_insert (health->history, measured);
+ goodix_health_estimate = estimate;
+ difference = ABS ((gint32) measured - estimate);
+ if (operation == 0)
+ {
+ guint16 mean;
+ guint length = MIN (goodix_health_enroll_checks, 4);
+ gint16 statistic = goodix_health_statistic (health->history, length, &mean);
+
+ health->enroll_allowed = estimate < GOODIX_HEALTH_ENROLL_THRESHOLD &&
+ (measured < GOODIX_HEALTH_ENROLL_THRESHOLD || statistic > 10);
+ fp_dbg ("Health enrollment checks=%u length=%u statistic=%d",
+ goodix_health_enroll_checks, length, statistic);
+ }
+ else
+ {
+ health->study_allowed = measured < GOODIX_HEALTH_STUDY_THRESHOLD &&
+ estimate < GOODIX_HEALTH_STUDY_THRESHOLD && difference < 20;
+ health->enroll_allowed = measured < GOODIX_HEALTH_ENROLL_THRESHOLD;
+ }
+ g_mutex_unlock (&goodix_health_lock);
+ fp_dbg ("Health operation=%u measured=%u estimate=%u difference=%u enroll=%d study=%d",
+ operation, measured, estimate, difference,
+ health->enroll_allowed, health->study_allowed);
+}
+
+void
+goodix_health_reset (GoodixSensorHealth *health)
+{
+ g_return_if_fail (health != NULL && !health->pair_active);
+ memset (health->history, 0, sizeof (health->history));
+ health->initialized = TRUE;
+ health->boot_seeded = FALSE;
+ health->enroll_allowed = TRUE;
+ health->study_allowed = FALSE;
+ health->complete = TRUE;
+}
+
+void
+goodix_health_note_capture (GoodixSensorHealth *health, gboolean enroll)
+{
+ g_return_if_fail (health != NULL && health->initialized);
+ health->operation = enroll ? 0 : 1;
+}
+
+void
+goodix_health_note_down (GoodixSensorHealth *health)
+{
+ g_return_if_fail (health != NULL && health->initialized);
+ health->study_allowed = FALSE;
+ health->complete = FALSE;
+}
+
+void
+goodix_health_seed_base (GoodixSensorHealth *health,
+ const GoodixHealthMeasurement *measurement)
+{
+ g_return_if_fail (health != NULL && health->initialized);
+ g_return_if_fail (measurement != NULL);
+ if (health->boot_seeded || !measurement->available)
+ return;
+ g_mutex_lock (&goodix_health_lock);
+ for (guint i = 0; i < G_N_ELEMENTS (health->history); i++)
+ health->history[i] = measurement->broken_pixels;
+ goodix_health_estimate = measurement->broken_pixels;
+ health->boot_seeded = TRUE;
+ g_mutex_unlock (&goodix_health_lock);
+}
+
+gboolean
+goodix_health_enroll_allowed (const GoodixSensorHealth *health)
+{
+ g_return_val_if_fail (health != NULL && health->initialized, FALSE);
+ return health->enroll_allowed;
+}
+
+gboolean
+goodix_health_is_complete (const GoodixSensorHealth *health)
+{
+ g_return_val_if_fail (health != NULL && health->initialized, FALSE);
+ return health->complete;
+}
+
+gboolean
+goodix_health_finish_deactivation (GoodixSensorHealth *health)
+{
+ g_return_val_if_fail (health != NULL && health->initialized, FALSE);
+ health->complete = TRUE;
+ g_mutex_lock (&goodix_health_lock);
+ goodix_health_enroll_checks = 0;
+ g_mutex_unlock (&goodix_health_lock);
+ return health->study_allowed;
+}
+
+typedef enum {
+ GOODIX_HEALTH_FIRST,
+ GOODIX_HEALTH_SECOND,
+ GOODIX_HEALTH_MEASURE,
+ GOODIX_HEALTH_NUM_STATES,
+} GoodixHealthState;
+
+typedef struct
+{
+ GoodixHealthPairPurpose purpose;
+ GoodixHealthDone done;
+ gpointer user_data;
+ guint32 operation;
+ guint16 *frames[2];
+ GoodixHealthMeasurement measurement;
+} GoodixHealthPair;
+
+static void
+goodix_health_pair_free (GoodixHealthPair *pair)
+{
+ g_free (pair->frames[0]);
+ g_free (pair->frames[1]);
+ g_free (pair);
+}
+
+static void
+goodix_health_image_done (FpDevice *dev, const GoodixTransportResult *result,
+ GError *error, gpointer user_data)
+{
+ FpiSsm *ssm = user_data;
+ GoodixHealthPair *pair = fpi_ssm_get_data (ssm);
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (error)
+ {
+ if (result->write_cancelled)
+ self->needs_reinit = TRUE;
+ if (result->ordinary_exhaustion)
+ {
+ fp_dbg ("Health image acquisition exhausted: %s", error->message);
+ g_clear_error (&error);
+ fpi_ssm_mark_completed (ssm);
+ }
+ else
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ }
+ return;
+ }
+ pair->frames[fpi_ssm_get_cur_state (ssm)] = goodix_cmd_dup_image_reply (dev, &error);
+ if (error)
+ {
+ /* Native raw-read status -1 is ordinary even when the command ACK and
+ * image event completed. It does not replace the caller's old state. */
+ fp_dbg ("Health raw image unavailable: %s", error->message);
+ g_clear_error (&error);
+ fpi_ssm_mark_completed (ssm);
+ return;
+ }
+ fpi_ssm_next_state (ssm);
+}
+
+static void
+goodix_health_pair_handler (FpiSsm *ssm, FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixHealthPair *pair = fpi_ssm_get_data (ssm);
+ guint state = fpi_ssm_get_cur_state (ssm);
+
+ if (state == GOODIX_HEALTH_MEASURE)
+ {
+ pair->measurement.broken_pixels = goodix_health_measure (pair->frames[0], pair->frames[1]);
+ pair->measurement.available = TRUE;
+ if (pair->purpose == GOODIX_HEALTH_PAIR_UP)
+ goodix_health_evaluate (&self->health, pair->operation, pair->measurement.broken_pixels);
+ fpi_ssm_mark_completed (ssm);
+ return;
+ }
+ else
+ {
+ guint16 dac = self->calib.dac_l;
+ guint8 payload[4];
+ GoodixTransportRequest request = {
+ .cmd = { 2, 0, payload, sizeof (payload), TRUE },
+ .expect_data = TRUE,
+ };
+
+ if (state == GOODIX_HEALTH_SECOND)
+ dac -= self->calib.dac_delta;
+ /* usbinterface!012d38 -> 0055d0 -> 0074bc: TX on, configured HV six,
+ * no finger flag. Mode 2/3 is not encoded. Use the existing command
+ * transport directly to retain its ordinary-exhaustion classification. */
+ payload[0] = 0x01;
+ payload[1] = 6;
+ payload[2] = dac & 0xff;
+ payload[3] = dac >> 8;
+ goodix_transport_command (dev, &request, goodix_health_image_done, ssm);
+ }
+}
+
+static void
+goodix_health_pair_done (FpiSsm *ssm, FpDevice *dev, GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixHealthPair *pair = fpi_ssm_get_data (ssm);
+
+ self->health.pair_active = FALSE;
+ if (!error && pair->purpose == GOODIX_HEALTH_PAIR_UP)
+ self->health.complete = TRUE;
+ pair->done (dev, &pair->measurement, error, pair->user_data);
+}
+
+void
+goodix_health_start_pair (FpDevice *dev, GoodixHealthPairPurpose purpose,
+ GoodixHealthDone done, gpointer user_data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixHealthPair *pair;
+ FpiSsm *ssm;
+
+ g_return_if_fail (done != NULL);
+ if (!self->health.initialized || self->health.pair_active || self->transport ||
+ (purpose != GOODIX_HEALTH_PAIR_BASE && purpose != GOODIX_HEALTH_PAIR_UP))
+ {
+ GoodixHealthMeasurement unavailable = { 0 };
+
+ done (dev, &unavailable,
+ fpi_device_error_new_msg (FP_DEVICE_ERROR_BUSY, "Sensor health owner is unavailable"),
+ user_data);
+ return;
+ }
+ pair = g_new0 (GoodixHealthPair, 1);
+ pair->purpose = purpose;
+ pair->done = done;
+ pair->user_data = user_data;
+ pair->operation = self->health.operation;
+ self->health.pair_active = TRUE;
+ if (purpose == GOODIX_HEALTH_PAIR_UP && pair->operation == 0)
+ {
+ g_mutex_lock (&goodix_health_lock);
+ goodix_health_enroll_checks++;
+ g_mutex_unlock (&goodix_health_lock);
+ }
+ ssm = fpi_ssm_new (dev, goodix_health_pair_handler, GOODIX_HEALTH_NUM_STATES);
+ fpi_ssm_set_data (ssm, pair, (GDestroyNotify) goodix_health_pair_free);
+ fpi_ssm_start (ssm, goodix_health_pair_done);
+}
diff --git a/libfprint/drivers/goodix53x5/device/health.h b/libfprint/drivers/goodix53x5/device/health.h
new file mode 100644
index 0000000..6f08ff4
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/health.h
@@ -0,0 +1,85 @@
+/*
+ * Goodix 53x5 driver for libfprint - profile-9 sensor health
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ * SPDX-License-Identifier: LGPL-2.1-or-later
+ */
+
+#pragma once
+
+#include "fpi-device.h"
+
+/* Per-HAL owners. The module's previous estimate and enrollment-check count
+ * deliberately survive reset; operation also survives a same-owner reset.
+ * All access to this struct belongs to the device's serialized main context. */
+typedef struct
+{
+ guint16 history[30];
+ guint32 operation;
+ gboolean initialized;
+ gboolean boot_seeded;
+ gboolean enroll_allowed;
+ gboolean study_allowed;
+ gboolean complete;
+ gboolean pair_active;
+} GoodixSensorHealth;
+
+typedef struct
+{
+ gboolean available;
+ guint16 broken_pixels;
+} GoodixHealthMeasurement;
+
+typedef enum {
+ GOODIX_HEALTH_PAIR_BASE,
+ GOODIX_HEALTH_PAIR_UP,
+} GoodixHealthPairPurpose;
+
+/* Measurement is borrowed for this callback; copy it if BASE admission follows
+ * later. Error ownership transfers to the callback. An ordinary failed pair
+ * returns !available with no error; terminal host failures return an error. */
+typedef void (*GoodixHealthDone) (FpDevice *dev,
+ const GoodixHealthMeasurement *measurement,
+ GError *error,
+ gpointer user_data);
+
+/* Actual cold HAL construction only, never a claim/capture/refresh boundary.
+ * Selects the compiled enabled defaults and native missing-history-file branch.
+ * No disk I/O. Zero-initialize a newly allocated owner before its first reset.
+ * Reset/destruction requires the caller to join any outstanding pair first. */
+void goodix_health_reset (GoodixSensorHealth *health);
+
+/* Request admission, not hardware-read retry: retain zero for enrollment,
+ * one for identify/verify. Request completion/cancellation does not clear it. */
+void goodix_health_note_capture (GoodixSensorHealth *health,
+ gboolean enroll);
+
+/* Call before the selected down handler's manual validation, even false down. */
+void goodix_health_note_down (GoodixSensorHealth *health);
+
+/* Caller serializes this child with all other hardware work and keeps the HAL
+ * owner alive through done. BASE belongs after TX-off manual FDT, before its
+ * comparison. UP belongs after the reference decision and before down-arm;
+ * caller must check retained image validity (not FDT-base validity).
+ * The child owns/frees both frames and never changes reference/generation/DAC.
+ * Ordinary UP failure still signals complete; terminal interruption does not. */
+void goodix_health_start_pair (FpDevice *dev,
+ GoodixHealthPairPurpose purpose,
+ GoodixHealthDone done,
+ gpointer user_data);
+
+/* Only after complete reference admission. A rejected base never seeds, and
+ * ordinary pair failure must not reject an otherwise admitted reference. */
+void goodix_health_seed_base (GoodixSensorHealth *health,
+ const GoodixHealthMeasurement *measurement);
+
+/* Snapshot at completed live callback publication, before that cycle's UP. */
+gboolean goodix_health_enroll_allowed (const GoodixSensorHealth *health);
+
+/* Deactivation owns one bounded wait, not a polling loop. Inspect complete at
+ * entry: if false, wait for the UP done callback or 1500 ms, then finish below
+ * before sleep. The caller must also join selected hardware work before issuing
+ * another command. finish re-signals completion and resets the module counter
+ * even on timeout, returning the retained study byte (not a study-work gate). */
+#define GOODIX_HEALTH_DEACTIVATE_TIMEOUT_MS 1500
+gboolean goodix_health_is_complete (const GoodixSensorHealth *health);
+gboolean goodix_health_finish_deactivation (GoodixSensorHealth *health);
diff --git a/libfprint/drivers/goodix53x5/device/image.c b/libfprint/drivers/goodix53x5/device/image.c
new file mode 100644
index 0000000..4436461
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/image.c
@@ -0,0 +1,62 @@
+/*
+ * Goodix 53x5 driver for libfprint — Image decoding and preprocessing
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/image.h"
+
+/**
+ * goodix_device_decode_image:
+ *
+ * Decode 12-bit packed image data to 16-bit pixel array.
+ * 6 bytes → 4 pixels, matching tool.py decode_image().
+ *
+ * Returns newly allocated array of GOODIX_SENSOR_PIXELS guint16 values, or
+ * NULL if the decrypted payload is too short for a full raw12 frame.
+ */
+guint16 *
+goodix_device_decode_image (const guint8 *data,
+ gsize data_len)
+{
+ guint16 *image;
+ gsize pixel_idx = 0;
+
+ if (data_len < GOODIX_SENSOR_RAW12_BYTES)
+ {
+ fp_warn ("Truncated raw12 image payload: %zu < %d",
+ data_len, GOODIX_SENSOR_RAW12_BYTES);
+ return NULL;
+ }
+
+ image = g_new0 (guint16, GOODIX_SENSOR_PIXELS);
+
+ for (gsize i = 0; i + 5 < data_len && pixel_idx + 3 < GOODIX_SENSOR_PIXELS; i += 6)
+ {
+ /* 6 bytes → 4 pixels of 12 bits each.
+ * Byte order matches tool.py decode_image() — NOT standard LE packed. */
+ image[pixel_idx++] = ((data[i + 0] & 0x0F) << 8) | data[i + 1];
+ image[pixel_idx++] = ((guint16) data[i + 3] << 4) | (data[i + 0] >> 4);
+ image[pixel_idx++] = ((data[i + 5] & 0x0F) << 8) | data[i + 2];
+ image[pixel_idx++] = ((guint16) data[i + 4] << 4) | (data[i + 5] >> 4);
+ }
+
+ return image;
+}
diff --git a/libfprint/drivers/goodix53x5/device/image.h b/libfprint/drivers/goodix53x5/device/image.h
new file mode 100644
index 0000000..ed170ba
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/image.h
@@ -0,0 +1,25 @@
+/*
+ * Goodix 53x5 driver for libfprint — Image decoding and preprocessing
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#pragma once
+
+#include "driver-private.h"
+
+guint16 *goodix_device_decode_image (const guint8 *data,
+ gsize data_len);
diff --git a/libfprint/drivers/goodix53x5/device/persistence.c b/libfprint/drivers/goodix53x5/device/persistence.c
new file mode 100644
index 0000000..9364e1a
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/persistence.c
@@ -0,0 +1,806 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan preprocessing persistence
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/persistence.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <glib/gstdio.h>
+
+#define GOODIX_MILAN_STATE_DIR "/var/lib/fprint"
+#define GOODIX_MILAN_STATE_PREFIX "goodix53x5-preprocess-"
+#define GOODIX_MILAN_STATE_VERSION 2u
+#define GOODIX_MILAN_STATE_HEADER_SIZE 64u
+#define GOODIX_MILAN_STATE_SAMPLE_FORMAT 2u
+#define GOODIX_MILAN_STATE_CALIBRATION_SIZE \
+ (GOODIX_MILAN_SENSOR_PIXELS * sizeof (guint16))
+#define GOODIX_MILAN_STATE_RING_PLANES_SIZE \
+ (3u * GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS)
+#define GOODIX_MILAN_STATE_AGE_PLANE_SIZE GOODIX_MILAN_SENSOR_PIXELS
+#define GOODIX_MILAN_STATE_REFERENCE_ROWS (GOODIX_MILAN_SENSOR_ROWS / 2u)
+#define GOODIX_MILAN_STATE_REFERENCE_COLUMNS (GOODIX_MILAN_SENSOR_COLUMNS / 2u)
+#define GOODIX_MILAN_STATE_REFERENCE_VALUES \
+ (GOODIX_MILAN_STATE_REFERENCE_ROWS * GOODIX_MILAN_STATE_REFERENCE_COLUMNS)
+#define GOODIX_MILAN_STATE_REFERENCE_SIZE \
+ (GOODIX_MILAN_STATE_REFERENCE_VALUES * sizeof (guint16))
+#define GOODIX_MILAN_STATE_DIGEST_SIZE 32u
+#define GOODIX_MILAN_STATE_PAYLOAD_OFFSET GOODIX_MILAN_STATE_HEADER_SIZE
+#define GOODIX_MILAN_STATE_CALIBRATION_OFFSET GOODIX_MILAN_STATE_PAYLOAD_OFFSET
+#define GOODIX_MILAN_STATE_RING_COUNT_OFFSET \
+ (GOODIX_MILAN_STATE_CALIBRATION_OFFSET + GOODIX_MILAN_STATE_CALIBRATION_SIZE)
+#define GOODIX_MILAN_STATE_COMPONENT_COUNT_OFFSET \
+ (GOODIX_MILAN_STATE_RING_COUNT_OFFSET + 1u)
+#define GOODIX_MILAN_STATE_REFERENCE_COUNT_OFFSET \
+ (GOODIX_MILAN_STATE_COMPONENT_COUNT_OFFSET + 1u)
+#define GOODIX_MILAN_STATE_RING_PLANES_OFFSET \
+ (GOODIX_MILAN_STATE_REFERENCE_COUNT_OFFSET + 1u)
+#define GOODIX_MILAN_STATE_COMPONENT_AGES_OFFSET \
+ (GOODIX_MILAN_STATE_RING_PLANES_OFFSET + GOODIX_MILAN_STATE_RING_PLANES_SIZE)
+#define GOODIX_MILAN_STATE_SUPPORT_AGES_OFFSET \
+ (GOODIX_MILAN_STATE_COMPONENT_AGES_OFFSET + GOODIX_MILAN_STATE_AGE_PLANE_SIZE)
+#define GOODIX_MILAN_STATE_REFERENCE_OFFSET \
+ (GOODIX_MILAN_STATE_SUPPORT_AGES_OFFSET + GOODIX_MILAN_STATE_AGE_PLANE_SIZE)
+#define GOODIX_MILAN_STATE_PAYLOAD_SIZE \
+ (GOODIX_MILAN_STATE_REFERENCE_OFFSET + GOODIX_MILAN_STATE_REFERENCE_SIZE - \
+ GOODIX_MILAN_STATE_PAYLOAD_OFFSET)
+#define GOODIX_MILAN_STATE_DIGEST_OFFSET \
+ (GOODIX_MILAN_STATE_PAYLOAD_OFFSET + GOODIX_MILAN_STATE_PAYLOAD_SIZE)
+#define GOODIX_MILAN_STATE_FILE_SIZE \
+ (GOODIX_MILAN_STATE_DIGEST_OFFSET + GOODIX_MILAN_STATE_DIGEST_SIZE)
+#define GOODIX_MILAN_STATE_MAX_SAMPLE_COUNT 400u
+
+enum {
+ GOODIX_MILAN_STATE_MAGIC_OFFSET = 0,
+ GOODIX_MILAN_STATE_VERSION_OFFSET = 8,
+ GOODIX_MILAN_STATE_HEADER_SIZE_OFFSET = 12,
+ GOODIX_MILAN_STATE_SUBTYPE_OFFSET = 16,
+ GOODIX_MILAN_STATE_ROWS_OFFSET = 18,
+ GOODIX_MILAN_STATE_COLUMNS_OFFSET = 20,
+ GOODIX_MILAN_STATE_SAMPLE_FORMAT_OFFSET = 22,
+ GOODIX_MILAN_STATE_SAMPLE_COUNT_OFFSET = 24,
+ GOODIX_MILAN_STATE_PAYLOAD_SIZE_OFFSET = 28,
+ GOODIX_MILAN_STATE_IDENTITY_OFFSET = 32,
+};
+
+static const guint8 goodix_milan_state_magic[8] = {
+ 'G', '5', '3', 'P', '9', 'P', 'S', '\0'
+};
+static const gchar goodix_milan_identity_domain[] =
+ "goodix53x5-preprocess-v2";
+
+/* Selected at sample delivery, immutable until the setup worker publishes it.
+ * Neither the destination nor the bytes borrow the device or live generation. */
+struct _GoodixMilanSetupSave
+{
+ gchar *path;
+ guint8 *contents;
+};
+
+static void
+goodix_milan_write_u16 (guint8 *output,
+ guint16 value)
+{
+ value = GUINT16_TO_LE (value);
+ memcpy (output, &value, sizeof (value));
+}
+
+static void
+goodix_milan_write_u32 (guint8 *output,
+ guint32 value)
+{
+ value = GUINT32_TO_LE (value);
+ memcpy (output, &value, sizeof (value));
+}
+
+static guint16
+goodix_milan_read_u16 (const guint8 *input)
+{
+ guint16 value;
+
+ memcpy (&value, input, sizeof (value));
+ return GUINT16_FROM_LE (value);
+}
+
+static guint32
+goodix_milan_read_u32 (const guint8 *input)
+{
+ guint32 value;
+
+ memcpy (&value, input, sizeof (value));
+ return GUINT32_FROM_LE (value);
+}
+
+static gint32
+goodix_milan_shift_right (gint32 value,
+ guint shift)
+{
+ guint32 bits = (guint32) value;
+
+ if (value >= 0)
+ return (gint32) (bits >> shift);
+ return (gint32) ((bits >> shift) |
+ (~UINT32_C (0) << (32u - shift)));
+}
+
+static void
+goodix_milan_restore_reference (const guint8 *packed,
+ guint16 *output)
+{
+ gint16 source[GOODIX_MILAN_STATE_REFERENCE_VALUES];
+
+ for (gsize i = 0; i < G_N_ELEMENTS (source); i++)
+ source[i] = (gint16) goodix_milan_read_u16 (packed + i * sizeof (guint16));
+
+ for (gsize row = 0; row < GOODIX_MILAN_SENSOR_ROWS; row++)
+ for (gsize column = 0; column < GOODIX_MILAN_SENSOR_COLUMNS; column++)
+ {
+ gsize source_row = row / 2u;
+ gsize source_column = column / 2u;
+ gint32 values[4];
+ guint value_count = 0;
+ gint32 value;
+
+ for (gsize y = source_row;
+ y < source_row + 2u && y < GOODIX_MILAN_STATE_REFERENCE_ROWS;
+ y++)
+ for (gsize x = source_column;
+ x < source_column + 2u &&
+ x < GOODIX_MILAN_STATE_REFERENCE_COLUMNS;
+ x++)
+ values[value_count++] =
+ source[y * GOODIX_MILAN_STATE_REFERENCE_COLUMNS + x];
+
+ if (value_count == 4)
+ {
+ gint32 fx = (column & 1u) ? 128 : 0;
+ gint32 fy = (row & 1u) ? 128 : 0;
+ guint32 weighted =
+ (guint32) values[0] * (guint32) (256 - fx) *
+ (guint32) (256 - fy) +
+ (guint32) values[1] * (guint32) fx *
+ (guint32) (256 - fy) +
+ (guint32) values[2] * (guint32) (256 - fx) * (guint32) fy +
+ (guint32) values[3] * (guint32) fx * (guint32) fy + 0x8000u;
+
+ value = goodix_milan_shift_right ((gint32) weighted, 16);
+ }
+ else
+ {
+ gint32 sum = 0;
+
+ for (guint i = 0; i < value_count; i++)
+ sum += values[i];
+ value = sum / (gint32) value_count;
+ }
+ output[row * GOODIX_MILAN_SENSOR_COLUMNS + column] =
+ (guint16) (gint16) value;
+ }
+}
+
+static void
+goodix_milan_store_reference (const guint16 *input,
+ guint8 *packed)
+{
+ for (gsize row = 0; row < GOODIX_MILAN_STATE_REFERENCE_ROWS; row++)
+ for (gsize column = 0; column < GOODIX_MILAN_STATE_REFERENCE_COLUMNS;
+ column++)
+ {
+ gsize source = row * 2u * GOODIX_MILAN_SENSOR_COLUMNS + column * 2u;
+ gint32 sum = (gint16) input[source] +
+ (gint16) input[source + 1] +
+ (gint16) input[source + GOODIX_MILAN_SENSOR_COLUMNS] +
+ (gint16) input[source + GOODIX_MILAN_SENSOR_COLUMNS + 1];
+
+ goodix_milan_write_u16 (
+ packed + (row * GOODIX_MILAN_STATE_REFERENCE_COLUMNS + column) *
+ sizeof (guint16),
+ (guint16) (gint16) goodix_milan_shift_right (sum, 2));
+ }
+}
+
+static void
+goodix_milan_sha256 (const guint8 *data,
+ gsize size,
+ guint8 digest[GOODIX_MILAN_STATE_DIGEST_SIZE])
+{
+ g_autoptr(GChecksum) checksum = g_checksum_new (G_CHECKSUM_SHA256);
+ gsize digest_size = GOODIX_MILAN_STATE_DIGEST_SIZE;
+
+ g_checksum_update (checksum, data, size);
+ g_checksum_get_digest (checksum, digest, &digest_size);
+}
+
+static gchar *
+goodix_milan_state_path (const gchar *prefix,
+ const guint8 identity[GOODIX_MILAN_STATE_DIGEST_SIZE])
+{
+ static const gchar hex[] = "0123456789abcdef";
+ gchar encoded[GOODIX_MILAN_STATE_DIGEST_SIZE * 2 + 1];
+
+ for (gsize i = 0; i < GOODIX_MILAN_STATE_DIGEST_SIZE; i++)
+ {
+ encoded[i * 2] = hex[identity[i] >> 4];
+ encoded[i * 2 + 1] = hex[identity[i] & 0x0f];
+ }
+ encoded[sizeof (encoded) - 1] = '\0';
+ return g_strdup_printf (GOODIX_MILAN_STATE_DIR "/%s%s.bin", prefix, encoded);
+}
+
+static void
+goodix_milan_state_header (guint8 *contents,
+ FpiDeviceGoodix53x5 *self,
+ guint32 sample_count)
+{
+ memcpy (contents + GOODIX_MILAN_STATE_MAGIC_OFFSET,
+ goodix_milan_state_magic, sizeof (goodix_milan_state_magic));
+ goodix_milan_write_u32 (contents + GOODIX_MILAN_STATE_VERSION_OFFSET,
+ GOODIX_MILAN_STATE_VERSION);
+ goodix_milan_write_u32 (contents + GOODIX_MILAN_STATE_HEADER_SIZE_OFFSET,
+ GOODIX_MILAN_STATE_HEADER_SIZE);
+ goodix_milan_write_u16 (contents + GOODIX_MILAN_STATE_SUBTYPE_OFFSET,
+ self->milan_sensor_subtype);
+ goodix_milan_write_u16 (contents + GOODIX_MILAN_STATE_ROWS_OFFSET,
+ GOODIX_MILAN_SENSOR_ROWS);
+ goodix_milan_write_u16 (contents + GOODIX_MILAN_STATE_COLUMNS_OFFSET,
+ GOODIX_MILAN_SENSOR_COLUMNS);
+ goodix_milan_write_u16 (contents + GOODIX_MILAN_STATE_SAMPLE_FORMAT_OFFSET,
+ GOODIX_MILAN_STATE_SAMPLE_FORMAT);
+ goodix_milan_write_u32 (contents + GOODIX_MILAN_STATE_SAMPLE_COUNT_OFFSET,
+ sample_count);
+ goodix_milan_write_u32 (contents + GOODIX_MILAN_STATE_PAYLOAD_SIZE_OFFSET,
+ GOODIX_MILAN_STATE_PAYLOAD_SIZE);
+ memcpy (contents + GOODIX_MILAN_STATE_IDENTITY_OFFSET,
+ self->milan_persistence_identity,
+ sizeof (self->milan_persistence_identity));
+}
+
+static gboolean
+goodix_milan_state_directory_secure (GError **error)
+{
+ GStatBuf stat_buffer;
+
+ if (g_lstat (GOODIX_MILAN_STATE_DIR, &stat_buffer) != 0)
+ {
+ int saved_errno = errno;
+
+ g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
+ "Failed to inspect %s: %s", GOODIX_MILAN_STATE_DIR,
+ g_strerror (saved_errno));
+ return FALSE;
+ }
+ if (!S_ISDIR (stat_buffer.st_mode) || stat_buffer.st_uid != geteuid () ||
+ (stat_buffer.st_mode & 0777) != 0700)
+ {
+ g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_ACCES,
+ "Milan state directory %s has unsafe ownership or permissions",
+ GOODIX_MILAN_STATE_DIR);
+ return FALSE;
+ }
+ return TRUE;
+}
+
+static gboolean
+goodix_milan_state_read (const gchar *path,
+ gsize size,
+ guint8 **contents,
+ GError **error)
+{
+ GStatBuf stat_buffer;
+ g_autofree guint8 *buffer = NULL;
+ gsize offset = 0;
+ int descriptor;
+
+ descriptor = g_open (path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, 0);
+ if (descriptor < 0)
+ {
+ int saved_errno = errno;
+
+ g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
+ "Failed to open %s: %s", path, g_strerror (saved_errno));
+ return FALSE;
+ }
+ if (fstat (descriptor, &stat_buffer) != 0 ||
+ !S_ISREG (stat_buffer.st_mode) || stat_buffer.st_uid != geteuid () ||
+ (stat_buffer.st_mode & 0777) != 0600 ||
+ stat_buffer.st_size != (goffset) size)
+ {
+ g_set_error (error, G_FILE_ERROR, G_FILE_ERROR_INVAL,
+ "Milan state %s has invalid size, ownership, or permissions",
+ path);
+ close (descriptor);
+ return FALSE;
+ }
+
+ buffer = g_malloc (size);
+ while (offset < size)
+ {
+ ssize_t bytes_read = read (descriptor, buffer + offset,
+ size - offset);
+
+ if (bytes_read < 0 && errno == EINTR)
+ continue;
+ if (bytes_read <= 0)
+ {
+ int saved_errno = bytes_read < 0 ? errno : EIO;
+
+ g_set_error (error, G_FILE_ERROR,
+ g_file_error_from_errno (saved_errno),
+ "Failed to read %s: %s", path,
+ g_strerror (saved_errno));
+ close (descriptor);
+ return FALSE;
+ }
+ offset += (gsize) bytes_read;
+ }
+ close (descriptor);
+ *contents = g_steal_pointer (&buffer);
+ return TRUE;
+}
+
+static int
+goodix_milan_state_open_directory (GError **error)
+{
+ GStatBuf stat_buffer;
+ int descriptor = -1;
+ int parent = -1;
+ int saved_errno;
+ int result;
+ gboolean created = FALSE;
+
+ descriptor = g_open (GOODIX_MILAN_STATE_DIR,
+ O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW, 0);
+ if (descriptor < 0 && errno == ENOENT)
+ {
+ /* /var/lib must already be provisioned durably. Own only the leaf's
+ * creation, including its link in that parent, not an ancestor tree. */
+ parent = g_open ("/var/lib",
+ O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW, 0);
+ if (parent < 0 || mkdirat (parent, "fprint", 0700) != 0)
+ goto fail;
+ created = TRUE;
+ descriptor = openat (parent, "fprint",
+ O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
+ }
+ if (descriptor < 0 || fstat (descriptor, &stat_buffer) != 0)
+ goto fail;
+ if (!S_ISDIR (stat_buffer.st_mode) || stat_buffer.st_uid != geteuid () ||
+ (stat_buffer.st_mode & 0777) != 0700)
+ {
+ errno = EACCES;
+ goto fail;
+ }
+ if (created)
+ {
+ if (fsync (parent) != 0)
+ goto fail;
+ created = FALSE;
+ /* Linux releases the descriptor even when close reports an error. */
+ result = close (parent);
+ parent = -1;
+ if (result != 0)
+ goto fail;
+ }
+ return descriptor;
+
+fail:
+ saved_errno = errno;
+ if (descriptor >= 0)
+ close (descriptor);
+ /* Remove an uncommitted, still-empty leaf so a retry repeats parent sync.
+ * As with temp cleanup, removal can itself fail under a filesystem fault. */
+ if (created)
+ unlinkat (parent, "fprint", AT_REMOVEDIR);
+ if (parent >= 0)
+ close (parent);
+ g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
+ "Failed to prepare %s: %s", GOODIX_MILAN_STATE_DIR,
+ g_strerror (saved_errno));
+ return -1;
+}
+
+static gboolean
+goodix_milan_state_write (const gchar *path,
+ const guint8 *contents,
+ gsize size,
+ GError **error)
+{
+ g_autofree gchar *uuid = NULL;
+ g_autofree gchar *temporary = NULL;
+ GStatBuf stat_buffer;
+ gsize offset = 0;
+ int directory;
+ int descriptor = -1;
+ int saved_errno;
+ int result;
+ gboolean temporary_exists = FALSE;
+
+ directory = goodix_milan_state_open_directory (error);
+ if (directory < 0)
+ return FALSE;
+ uuid = g_uuid_string_random ();
+ temporary = g_strdup_printf (".goodix53x5-%s.tmp", uuid);
+ descriptor = openat (directory, temporary,
+ O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600);
+ if (descriptor < 0)
+ goto fail;
+ temporary_exists = TRUE;
+ /* Never copy permissions from the previous destination. A restrictive umask
+ * may remove owner bits; fix those on our own inode before syncing it. */
+ if (fstat (descriptor, &stat_buffer) != 0 ||
+ ((stat_buffer.st_mode & 0777) != 0600 && fchmod (descriptor, 0600) != 0))
+ goto fail;
+ while (offset < size)
+ {
+ ssize_t written = write (descriptor, contents + offset, size - offset);
+
+ if (written < 0 && errno == EINTR)
+ continue;
+ if (written <= 0)
+ {
+ if (written == 0)
+ errno = EIO;
+ goto fail;
+ }
+ offset += (gsize) written;
+ }
+ if (fsync (descriptor) != 0)
+ goto fail;
+ result = close (descriptor);
+ descriptor = -1;
+ if (result != 0)
+ goto fail;
+ if (renameat (directory, temporary, directory, strrchr (path, '/') + 1) != 0)
+ goto fail;
+ temporary_exists = FALSE;
+ /* After rename the complete new file is visible. A directory sync failure
+ * means uncertain durability, not rollback. */
+ if (fsync (directory) != 0)
+ goto fail;
+ result = close (directory);
+ directory = -1;
+ if (result == 0)
+ return TRUE;
+
+fail:
+ saved_errno = errno;
+ if (descriptor >= 0)
+ close (descriptor);
+ if (temporary_exists)
+ unlinkat (directory, temporary, 0);
+ if (directory >= 0)
+ close (directory);
+ g_set_error (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
+ "Failed to save %s: %s", path, g_strerror (saved_errno));
+ return FALSE;
+}
+
+static gboolean
+goodix_milan_state_valid (
+ const guint8 *contents,
+ gsize size,
+ const guint8 identity[GOODIX_MILAN_STATE_DIGEST_SIZE],
+ guint16 subtype)
+{
+ guint8 digest[GOODIX_MILAN_STATE_DIGEST_SIZE];
+
+ if (size != GOODIX_MILAN_STATE_FILE_SIZE ||
+ memcmp (contents + GOODIX_MILAN_STATE_MAGIC_OFFSET,
+ goodix_milan_state_magic,
+ sizeof (goodix_milan_state_magic)) != 0 ||
+ goodix_milan_read_u32 (
+ contents + GOODIX_MILAN_STATE_VERSION_OFFSET) !=
+ GOODIX_MILAN_STATE_VERSION ||
+ goodix_milan_read_u32 (
+ contents + GOODIX_MILAN_STATE_HEADER_SIZE_OFFSET) !=
+ GOODIX_MILAN_STATE_HEADER_SIZE ||
+ goodix_milan_read_u16 (
+ contents + GOODIX_MILAN_STATE_SUBTYPE_OFFSET) != subtype ||
+ goodix_milan_read_u16 (contents + GOODIX_MILAN_STATE_ROWS_OFFSET) !=
+ GOODIX_MILAN_SENSOR_ROWS ||
+ goodix_milan_read_u16 (contents + GOODIX_MILAN_STATE_COLUMNS_OFFSET) !=
+ GOODIX_MILAN_SENSOR_COLUMNS ||
+ goodix_milan_read_u16 (
+ contents + GOODIX_MILAN_STATE_SAMPLE_FORMAT_OFFSET) !=
+ GOODIX_MILAN_STATE_SAMPLE_FORMAT ||
+ goodix_milan_read_u32 (
+ contents + GOODIX_MILAN_STATE_SAMPLE_COUNT_OFFSET) >
+ GOODIX_MILAN_STATE_MAX_SAMPLE_COUNT ||
+ goodix_milan_read_u32 (
+ contents + GOODIX_MILAN_STATE_PAYLOAD_SIZE_OFFSET) !=
+ GOODIX_MILAN_STATE_PAYLOAD_SIZE ||
+ memcmp (contents + GOODIX_MILAN_STATE_IDENTITY_OFFSET, identity,
+ GOODIX_MILAN_STATE_DIGEST_SIZE) != 0 ||
+ contents[GOODIX_MILAN_STATE_RING_COUNT_OFFSET] > 3u ||
+ contents[GOODIX_MILAN_STATE_COMPONENT_COUNT_OFFSET] > 5u ||
+ contents[GOODIX_MILAN_STATE_REFERENCE_COUNT_OFFSET] > 50u)
+ return FALSE;
+
+ for (gsize i = 0; i < GOODIX_MILAN_STATE_RING_PLANES_SIZE; i++)
+ if (contents[GOODIX_MILAN_STATE_RING_PLANES_OFFSET + i] > 2u)
+ return FALSE;
+ for (gsize i = 0; i < GOODIX_MILAN_STATE_AGE_PLANE_SIZE; i++)
+ if (contents[GOODIX_MILAN_STATE_COMPONENT_AGES_OFFSET + i] > 5u ||
+ contents[GOODIX_MILAN_STATE_SUPPORT_AGES_OFFSET + i] > 50u)
+ return FALSE;
+
+ goodix_milan_sha256 (contents, GOODIX_MILAN_STATE_DIGEST_OFFSET, digest);
+ return memcmp (contents + GOODIX_MILAN_STATE_DIGEST_OFFSET, digest,
+ sizeof (digest)) == 0;
+}
+
+void
+goodix_milan_persistence_prepare (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ g_autoptr(GChecksum) checksum = NULL;
+ guint8 encoded[10];
+ gsize digest_size = sizeof (self->milan_persistence_identity);
+
+ goodix_milan_persistence_clear (dev);
+ if (!self->otp_data || self->otp_len == 0 || self->otp_len > G_MAXUINT32)
+ {
+ fp_warn ("Cannot key Milan preprocessing state without verified OTP");
+ return;
+ }
+
+ goodix_milan_write_u32 (encoded, self->chip_id);
+ goodix_milan_write_u16 (encoded + 4, self->milan_sensor_subtype);
+ goodix_milan_write_u32 (encoded + 6, (guint32) self->otp_len);
+ checksum = g_checksum_new (G_CHECKSUM_SHA256);
+ g_checksum_update (checksum, (const guint8 *) goodix_milan_identity_domain,
+ sizeof (goodix_milan_identity_domain) - 1);
+ g_checksum_update (checksum, encoded, sizeof (encoded));
+ g_checksum_update (checksum, self->otp_data, self->otp_len);
+ g_checksum_get_digest (checksum, self->milan_persistence_identity,
+ &digest_size);
+ self->milan_persistence_identity_valid = TRUE;
+}
+
+void
+goodix_milan_persistence_clear (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ memset (self->milan_persistence_identity, 0,
+ sizeof (self->milan_persistence_identity));
+ self->milan_persistence_identity_valid = FALSE;
+}
+
+GoodixMilanSetupSave *
+goodix_milan_persistence_restore (FpDevice *dev,
+ GoodixMilanGeneration *generation)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ g_autofree guint8 *contents = NULL;
+ GoodixMilanPreprocessState *restored;
+ GoodixMilanSetupSave *save;
+
+ g_autoptr(GError) error = NULL;
+
+ g_return_val_if_fail (generation != NULL, NULL);
+ save = g_try_new0 (GoodixMilanSetupSave, 1);
+ if (!save)
+ return NULL;
+ if (!self->milan_persistence_identity_valid)
+ return save;
+ save->path = goodix_milan_state_path (GOODIX_MILAN_STATE_PREFIX,
+ self->milan_persistence_identity);
+
+ if (!goodix_milan_state_directory_secure (&error))
+ {
+ if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
+ fp_warn ("Cannot use Milan preprocessing state directory: %s",
+ error->message);
+ goto defaults;
+ }
+ if (!goodix_milan_state_read (save->path, GOODIX_MILAN_STATE_FILE_SIZE, &contents, &error))
+ {
+ if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
+ fp_warn ("Failed to read Milan preprocessing state %s: %s",
+ save->path, error->message);
+ goto defaults;
+ }
+ if (!goodix_milan_state_valid (contents, GOODIX_MILAN_STATE_FILE_SIZE,
+ self->milan_persistence_identity,
+ self->milan_sensor_subtype))
+ {
+ fp_warn ("Ignoring invalid Milan preprocessing state %s", save->path);
+ goto defaults;
+ }
+
+ /* The setup caller already reset this temporary generation. All validation
+ * precedes these writes; decoding the validated fixed-size fields cannot fail. */
+ restored = &generation->state;
+ /* Native import retains these fresh-DLL defaults, not persisted values. */
+ restored->profile9_history_mask_threshold = 60;
+ restored->profile9_history_mask_average = 60;
+ restored->sample_count = goodix_milan_read_u32 (
+ contents + GOODIX_MILAN_STATE_SAMPLE_COUNT_OFFSET);
+ for (gsize i = 0; i < GOODIX_MILAN_SENSOR_PIXELS; i++)
+ restored->calibration_map[i] = goodix_milan_read_u16 (
+ contents + GOODIX_MILAN_STATE_CALIBRATION_OFFSET +
+ i * sizeof (guint16));
+ restored->extraction_classification.retained_count =
+ contents[GOODIX_MILAN_STATE_RING_COUNT_OFFSET];
+ restored->extraction_persistence.retained_count =
+ contents[GOODIX_MILAN_STATE_RING_COUNT_OFFSET];
+ memcpy (restored->extraction_classification.retained_class_planes,
+ contents + GOODIX_MILAN_STATE_RING_PLANES_OFFSET,
+ GOODIX_MILAN_STATE_RING_PLANES_SIZE);
+ memcpy (restored->extraction_persistence.retained_class_planes,
+ contents + GOODIX_MILAN_STATE_RING_PLANES_OFFSET,
+ GOODIX_MILAN_STATE_RING_PLANES_SIZE);
+ restored->profile9_history_update_count =
+ contents[GOODIX_MILAN_STATE_COMPONENT_COUNT_OFFSET];
+ restored->profile9_history_count =
+ contents[GOODIX_MILAN_STATE_REFERENCE_COUNT_OFFSET];
+ memcpy (restored->profile9_component_age,
+ contents + GOODIX_MILAN_STATE_COMPONENT_AGES_OFFSET,
+ GOODIX_MILAN_STATE_AGE_PLANE_SIZE);
+ memcpy (restored->profile9_reference_age,
+ contents + GOODIX_MILAN_STATE_SUPPORT_AGES_OFFSET,
+ GOODIX_MILAN_STATE_AGE_PLANE_SIZE);
+ goodix_milan_restore_reference (
+ contents + GOODIX_MILAN_STATE_REFERENCE_OFFSET,
+ restored->profile9_history_reference);
+ fp_info ("Restored Milan preprocessing state with %u samples",
+ generation->state.sample_count);
+ /* Setup changes no compact-format field. Keep the original packed reference
+ * and packet instead of encoding the reconstructed or transferred globals. */
+ save->contents = g_steal_pointer (&contents);
+ return save;
+
+defaults:
+ save->contents = g_try_malloc0 (GOODIX_MILAN_STATE_FILE_SIZE);
+ if (save->contents)
+ {
+ /* Native default calibration is unity before the first live initializer
+ * clears it. The immediate setup-save must retain that pre-live value. */
+ goodix_milan_state_header (save->contents, self, 0);
+ for (gsize i = 0; i < GOODIX_MILAN_SENSOR_PIXELS; i++)
+ goodix_milan_write_u16 (
+ save->contents + GOODIX_MILAN_STATE_CALIBRATION_OFFSET +
+ i * sizeof (guint16), 0x2000);
+ goodix_milan_sha256 (save->contents, GOODIX_MILAN_STATE_DIGEST_OFFSET,
+ save->contents + GOODIX_MILAN_STATE_DIGEST_OFFSET);
+ }
+ return save;
+}
+
+void
+goodix_milan_setup_save_free (GoodixMilanSetupSave *save)
+{
+ if (!save)
+ return;
+ g_free (save->path);
+ g_free (save->contents);
+ g_free (save);
+}
+
+static gint32
+goodix_milan_setup_save_publish (gpointer user_data)
+{
+ GoodixMilanSetupSave *save = user_data;
+
+ g_autoptr(GError) error = NULL;
+
+ if (!save || (save->path && !save->contents))
+ return 0x8001;
+ if (!save->path)
+ return 0x8002;
+ if (!goodix_milan_state_write (save->path, save->contents,
+ GOODIX_MILAN_STATE_FILE_SIZE, &error))
+ fp_warn ("Failed to save Milan setup state %s: %s",
+ save->path, error->message);
+ return 0;
+}
+
+void
+goodix_milan_persistence_bind_setup (GoodixMilanRuntimeInput *input,
+ GoodixMilanGeneration *generation)
+{
+ g_return_if_fail (input != NULL);
+ g_return_if_fail (generation != NULL);
+ goodix_milan_runtime_input_set_setup_hook (
+ input, goodix_milan_setup_save_publish,
+ g_steal_pointer (&generation->setup_save),
+ (GDestroyNotify) goodix_milan_setup_save_free);
+}
+
+void
+goodix_milan_persistence_save (FpDevice *dev,
+ const GoodixMilanPreprocessState *state)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ g_autofree guint8 *contents = NULL;
+ g_autofree gchar *path = NULL;
+ const guint8 *retained_planes;
+
+ g_autoptr(GError) error = NULL;
+
+ if (!state || !self->milan_persistence_identity_valid)
+ return;
+ retained_planes = (const guint8 *)
+ state->extraction_persistence.retained_class_planes;
+ if (state->sample_count > GOODIX_MILAN_STATE_MAX_SAMPLE_COUNT)
+ {
+ fp_warn ("Refusing to save invalid Milan sample count %u",
+ state->sample_count);
+ return;
+ }
+ if (state->extraction_persistence.retained_count > 3u ||
+ state->profile9_history_update_count > 5u ||
+ state->profile9_history_count > 50u)
+ {
+ fp_warn ("Refusing to save invalid Milan retained-state counters");
+ return;
+ }
+ for (gsize i = 0; i < GOODIX_MILAN_STATE_RING_PLANES_SIZE; i++)
+ if (retained_planes[i] > 2u)
+ {
+ fp_warn ("Refusing to save invalid Milan retained class plane");
+ return;
+ }
+ for (gsize i = 0; i < GOODIX_MILAN_STATE_AGE_PLANE_SIZE; i++)
+ if (state->profile9_component_age[i] > 5u ||
+ state->profile9_reference_age[i] > 50u)
+ {
+ fp_warn ("Refusing to save invalid Milan retained age plane");
+ return;
+ }
+
+ contents = g_malloc0 (GOODIX_MILAN_STATE_FILE_SIZE);
+ goodix_milan_state_header (contents, self, state->sample_count);
+ for (gsize i = 0; i < GOODIX_MILAN_SENSOR_PIXELS; i++)
+ goodix_milan_write_u16 (
+ contents + GOODIX_MILAN_STATE_CALIBRATION_OFFSET +
+ i * sizeof (guint16),
+ state->calibration_map[i]);
+ contents[GOODIX_MILAN_STATE_RING_COUNT_OFFSET] =
+ (guint8) state->extraction_persistence.retained_count;
+ contents[GOODIX_MILAN_STATE_COMPONENT_COUNT_OFFSET] =
+ (guint8) state->profile9_history_update_count;
+ contents[GOODIX_MILAN_STATE_REFERENCE_COUNT_OFFSET] =
+ (guint8) state->profile9_history_count;
+ memcpy (contents + GOODIX_MILAN_STATE_RING_PLANES_OFFSET,
+ retained_planes,
+ GOODIX_MILAN_STATE_RING_PLANES_SIZE);
+ memcpy (contents + GOODIX_MILAN_STATE_COMPONENT_AGES_OFFSET,
+ state->profile9_component_age,
+ GOODIX_MILAN_STATE_AGE_PLANE_SIZE);
+ memcpy (contents + GOODIX_MILAN_STATE_SUPPORT_AGES_OFFSET,
+ state->profile9_reference_age,
+ GOODIX_MILAN_STATE_AGE_PLANE_SIZE);
+ goodix_milan_store_reference (
+ state->profile9_history_reference,
+ contents + GOODIX_MILAN_STATE_REFERENCE_OFFSET);
+ goodix_milan_sha256 (contents, GOODIX_MILAN_STATE_DIGEST_OFFSET,
+ contents + GOODIX_MILAN_STATE_DIGEST_OFFSET);
+
+ path = goodix_milan_state_path (GOODIX_MILAN_STATE_PREFIX,
+ self->milan_persistence_identity);
+ if (!goodix_milan_state_write (path, contents, GOODIX_MILAN_STATE_FILE_SIZE, &error))
+ {
+ fp_warn ("Failed to save Milan preprocessing state %s: %s",
+ path, error->message);
+ return;
+ }
+ fp_info ("Saved Milan preprocessing state with %u samples",
+ state->sample_count);
+}
diff --git a/libfprint/drivers/goodix53x5/device/persistence.h b/libfprint/drivers/goodix53x5/device/persistence.h
new file mode 100644
index 0000000..8cb49ca
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/persistence.h
@@ -0,0 +1,24 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan preprocessing persistence
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include "device/base.h"
+#include "milan/runtime.h"
+
+void goodix_milan_persistence_prepare (FpDevice *dev);
+void goodix_milan_persistence_clear (FpDevice *dev);
+GoodixMilanSetupSave *goodix_milan_persistence_restore (FpDevice *dev,
+ GoodixMilanGeneration *generation);
+void goodix_milan_setup_save_free (GoodixMilanSetupSave *save);
+void goodix_milan_persistence_bind_setup (GoodixMilanRuntimeInput *input,
+ GoodixMilanGeneration *generation);
+void goodix_milan_persistence_save (FpDevice *dev,
+ const GoodixMilanPreprocessState *state);
diff --git a/libfprint/drivers/goodix53x5/device/proto.c b/libfprint/drivers/goodix53x5/device/proto.c
new file mode 100644
index 0000000..110f359
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/proto.c
@@ -0,0 +1,370 @@
+/*
+ * Goodix 53x5 driver for libfprint — Protocol layer
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "device/proto.h"
+
+/*
+ * Message format: [cmd_byte(1)][size(2 LE)][payload(N)][checksum(1)]
+ * cmd_byte = category<<4 | command<<1
+ * size = len(payload) + 1 (for the checksum byte)
+ * checksum = (0xAA - sum(cmd_byte, size_lo, size_hi, payload...)) & 0xFF
+ * or 0x88 for handshake messages
+ */
+
+/**
+ * goodix_proto_build_message:
+ *
+ * Build a complete protocol message ready for chunked USB transmission.
+ * Returns a newly allocated buffer. The caller must free it with g_free().
+ */
+guint8 *
+goodix_proto_build_message (guint8 category,
+ guint8 command,
+ const guint8 *payload,
+ gsize payload_len,
+ gboolean use_checksum,
+ gsize *out_len)
+{
+ guint8 cmd_byte = (category << 4) | (command << 1);
+ guint16 size_field = (guint16) (payload_len + 1); /* +1 for checksum */
+ gsize total = 1 + 2 + payload_len + 1; /* cmd + size(2) + payload + checksum */
+ guint8 *msg = g_malloc (total);
+ guint8 checksum;
+ guint sum;
+
+ msg[0] = cmd_byte;
+ msg[1] = size_field & 0xFF;
+ msg[2] = (size_field >> 8) & 0xFF;
+
+ if (payload_len > 0)
+ memcpy (msg + 3, payload, payload_len);
+
+ if (use_checksum)
+ {
+ sum = 0;
+ for (gsize i = 0; i < total - 1; i++)
+ sum += msg[i];
+ checksum = (0xAA - sum) & 0xFF;
+ }
+ else
+ {
+ checksum = 0x88;
+ }
+
+ msg[total - 1] = checksum;
+
+ *out_len = total;
+ return msg;
+}
+
+/**
+ * goodix_proto_validate_checksum:
+ *
+ * Validate checksum of a complete received message.
+ * data must include the full message including the checksum byte.
+ */
+gboolean
+goodix_proto_validate_checksum (const guint8 *data,
+ gsize len)
+{
+ guint8 msg_checksum;
+ guint sum;
+ guint8 computed;
+
+ if (len < 4)
+ return FALSE;
+
+ msg_checksum = data[len - 1];
+
+ /* 0x88 = no-checksum marker (handshake) */
+ if (msg_checksum == 0x88)
+ return TRUE;
+
+ sum = 0;
+ for (gsize i = 0; i < len - 1; i++)
+ sum += data[i];
+
+ computed = (0xAA - sum) & 0xFF;
+ return computed == msg_checksum;
+}
+
+/**
+ * goodix_proto_rx_reset:
+ *
+ * Reset the reassembly buffer for a new message.
+ */
+void
+goodix_proto_rx_reset (GoodixReassembly *rx)
+{
+ if (rx->buf == NULL)
+ rx->buf = g_malloc (GOODIX_RX_BUF_SIZE);
+ rx->len = 0;
+ rx->expected = 0;
+ rx->cmd_byte = 0;
+}
+
+/**
+ * goodix_proto_rx_feed_chunk:
+ *
+ * Feed a USB chunk into the reassembly buffer.
+ * Returns TRUE if the chunk was accepted, FALSE on protocol error.
+ */
+gboolean
+goodix_proto_rx_feed_chunk (GoodixReassembly *rx,
+ const guint8 *chunk,
+ gsize chunk_len)
+{
+ if (chunk_len == 0)
+ return TRUE;
+
+ if (rx->len == 0)
+ {
+ /* First chunk of a new message */
+ if (chunk_len < 3)
+ return FALSE;
+
+ rx->cmd_byte = chunk[0];
+
+ guint16 msg_size = chunk[1] | ((guint16) chunk[2] << 8);
+
+ /* size_field stores payload + checksum, so the full message length is
+ * 3-byte header plus size_field bytes. Continuation chunks contribute
+ * only bytes after their leading continuation marker. */
+ rx->expected = (gsize) msg_size + 3;
+
+ /* Copy the entire first chunk */
+ if (rx->len + chunk_len > GOODIX_RX_BUF_SIZE)
+ return FALSE;
+ memcpy (rx->buf + rx->len, chunk, chunk_len);
+ rx->len += chunk_len;
+ }
+ else
+ {
+ /* Continuation chunk */
+ if (chunk_len < 1)
+ return FALSE;
+
+ guint8 contd_cmd = chunk[0];
+
+ /* Continuation marker: bit 0 set, and upper bits match */
+ if ((contd_cmd & 1) == 0 || (contd_cmd & 0xFE) != rx->cmd_byte)
+ {
+ fp_warn ("Wrong continuation chunk: got 0x%02x, expected 0x%02x|1",
+ contd_cmd, rx->cmd_byte);
+ return FALSE;
+ }
+
+ /* Skip the continuation cmd byte, copy rest */
+ if (rx->len + chunk_len - 1 > GOODIX_RX_BUF_SIZE)
+ return FALSE;
+ memcpy (rx->buf + rx->len, chunk + 1, chunk_len - 1);
+ rx->len += chunk_len - 1;
+ }
+
+ return TRUE;
+}
+
+/**
+ * goodix_proto_rx_complete:
+ *
+ * Check if the reassembly buffer has a complete message.
+ */
+gboolean
+goodix_proto_rx_complete (GoodixReassembly *rx)
+{
+ if (rx->expected == 0)
+ return FALSE;
+
+ /* We need at least 'expected' bytes. We may have more due to
+ * USB padding in the last chunk. */
+ return rx->len >= rx->expected;
+}
+
+/**
+ * goodix_proto_rx_parse:
+ *
+ * Parse the complete reassembled message.
+ * out_payload points into the rx buffer — valid until rx is reset.
+ */
+gboolean
+goodix_proto_rx_parse (GoodixReassembly *rx,
+ guint8 *out_category,
+ guint8 *out_command,
+ const guint8 **out_payload,
+ gsize *out_payload_len)
+{
+ gsize msg_len;
+
+ if (!goodix_proto_rx_complete (rx))
+ return FALSE;
+
+ msg_len = rx->expected;
+
+ /* Trim to actual message length */
+ if (msg_len < 4)
+ return FALSE;
+
+ /* Validate checksum */
+ if (!goodix_proto_validate_checksum (rx->buf, msg_len))
+ {
+ fp_warn ("Message checksum validation failed");
+ return FALSE;
+ }
+
+ *out_category = rx->buf[0] >> 4;
+ *out_command = (rx->buf[0] & 0x0F) >> 1;
+
+ /* Payload starts at offset 3, ends before checksum */
+ *out_payload = rx->buf + 3;
+ *out_payload_len = msg_len - 4; /* minus cmd(1) + size(2) + checksum(1) */
+
+ return TRUE;
+}
+
+/**
+ * goodix_proto_build_mcu_message:
+ *
+ * Build an MCU envelope payload.
+ * Format: [data_type(4 LE)][total_size(4 LE)][data]
+ * where total_size = len(data) + 8 (includes the header).
+ */
+void
+goodix_proto_build_mcu_message (guint32 data_type,
+ const guint8 *data,
+ gsize data_len,
+ guint8 **out_payload,
+ gsize *out_payload_len)
+{
+ gsize total = 4 + 4 + data_len;
+ guint8 *buf = g_malloc (total);
+ guint32 size_val = (guint32) (data_len + 8);
+
+ buf[0] = data_type & 0xFF;
+ buf[1] = (data_type >> 8) & 0xFF;
+ buf[2] = (data_type >> 16) & 0xFF;
+ buf[3] = (data_type >> 24) & 0xFF;
+
+ buf[4] = size_val & 0xFF;
+ buf[5] = (size_val >> 8) & 0xFF;
+ buf[6] = (size_val >> 16) & 0xFF;
+ buf[7] = (size_val >> 24) & 0xFF;
+
+ if (data_len > 0)
+ memcpy (buf + 8, data, data_len);
+
+ *out_payload = buf;
+ *out_payload_len = total;
+}
+
+/**
+ * goodix_proto_parse_mcu_message:
+ *
+ * Parse an MCU envelope from a received message payload.
+ * The received payload (from category=0xD, command=1) has format:
+ * [data_type(4 LE)][payload_size(4 LE)][data]
+ * where payload_size = total including the 8-byte header.
+ */
+gboolean
+goodix_proto_parse_mcu_message (const guint8 *payload,
+ gsize payload_len,
+ guint32 expected_type,
+ const guint8 **out_data,
+ gsize *out_data_len)
+{
+ guint32 msg_type, msg_size;
+
+ if (payload_len < 8)
+ return FALSE;
+
+ msg_type = payload[0] | ((guint32) payload[1] << 8) |
+ ((guint32) payload[2] << 16) | ((guint32) payload[3] << 24);
+
+ if (msg_type != expected_type)
+ {
+ fp_warn ("MCU message type mismatch: expected 0x%x, got 0x%x",
+ expected_type, msg_type);
+ return FALSE;
+ }
+
+ msg_size = payload[4] | ((guint32) payload[5] << 8) |
+ ((guint32) payload[6] << 16) | ((guint32) payload[7] << 24);
+
+ if (msg_size != (guint32) payload_len)
+ {
+ fp_warn ("MCU message size mismatch: header says %u, got %zu",
+ msg_size, payload_len);
+ return FALSE;
+ }
+
+ *out_data = payload + 8;
+ *out_data_len = payload_len - 8;
+ return TRUE;
+}
+
+/**
+ * goodix_proto_parse_production_read:
+ *
+ * Parse a production_read reply payload.
+ * Format: [status(1)][read_type(4 LE)][data_size(4 LE)][data]
+ */
+gboolean
+goodix_proto_parse_production_read (const guint8 *payload,
+ gsize payload_len,
+ guint32 expected_type,
+ const guint8 **out_data,
+ gsize *out_data_len)
+{
+ guint32 msg_type, data_size;
+
+ if (payload_len < 9)
+ return FALSE;
+
+ if (payload[0] != 0)
+ {
+ fp_warn ("Production read MCU failed, status: %d", payload[0]);
+ return FALSE;
+ }
+
+ msg_type = payload[1] | ((guint32) payload[2] << 8) |
+ ((guint32) payload[3] << 16) | ((guint32) payload[4] << 24);
+
+ if (msg_type != expected_type)
+ {
+ fp_warn ("Production read type mismatch: expected 0x%x, got 0x%x",
+ expected_type, msg_type);
+ return FALSE;
+ }
+
+ data_size = payload[5] | ((guint32) payload[6] << 8) |
+ ((guint32) payload[7] << 16) | ((guint32) payload[8] << 24);
+
+ if (data_size != payload_len - 9)
+ {
+ fp_warn ("Production read size mismatch: %u != %zu",
+ data_size, payload_len - 9);
+ return FALSE;
+ }
+
+ *out_data = payload + 9;
+ *out_data_len = data_size;
+ return TRUE;
+}
diff --git a/libfprint/drivers/goodix53x5/device/proto.h b/libfprint/drivers/goodix53x5/device/proto.h
new file mode 100644
index 0000000..3458995
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/proto.h
@@ -0,0 +1,100 @@
+/*
+ * Goodix 53x5 driver for libfprint — Protocol layer
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#pragma once
+
+#include <glib.h>
+
+/* Wire message format: [cmd_byte(1)][size(2 LE)][payload(N)][checksum(1)]
+ * cmd_byte = category<<4 | command<<1
+ * checksum = (0xAA - sum(all_bytes)) & 0xFF, or 0x88 for handshake */
+
+/* Message selectors more than one module names. */
+#define GOODIX_PROTO_CATEGORY_NOP 0x00
+#define GOODIX_PROTO_CATEGORY_IMAGE 0x02
+#define GOODIX_PROTO_CATEGORY_FDT 0x03
+#define GOODIX_PROTO_CMD_FDT_DOWN 0x01
+#define GOODIX_PROTO_CMD_FDT_UP 0x02
+#define GOODIX_PROTO_CMD_FDT_MANUAL 0x03
+#define GOODIX_PROTO_CATEGORY_REGISTER 0x08
+#define GOODIX_PROTO_CATEGORY_CONFIG 0x09
+#define GOODIX_PROTO_CMD_CONFIG_DOWNLOAD 0x0
+#define GOODIX_PROTO_CATEGORY_SYSTEM 0x0a
+#define GOODIX_PROTO_CATEGORY_ACK 0x0b
+#define GOODIX_PROTO_CMD_ACK 0x00
+#define GOODIX_PROTO_ACK_FLAG_VALID 0x01
+#define GOODIX_PROTO_CATEGORY_NOTICE 0x0c
+#define GOODIX_PROTO_CATEGORY_MCU 0x0d
+#define GOODIX_PROTO_CATEGORY_PRODUCTION 0x0e
+#define GOODIX_PROTO_CMD_PRODUCTION_WRITE 0x1
+#define GOODIX_PROTO_CATEGORY_FIRMWARE 0x0f
+
+/* Max reassembly buffer (encrypted image can be ~15KB) */
+#define GOODIX_RX_BUF_SIZE (16 * 1024)
+
+/* --- Reassembly buffer --- */
+typedef struct
+{
+ guint8 *buf; /* heap-allocated, GOODIX_RX_BUF_SIZE bytes */
+ gsize len; /* bytes accumulated */
+ gsize expected; /* total message size from header (including header+checksum) */
+ guint8 cmd_byte; /* command byte from first chunk */
+} GoodixReassembly;
+
+guint8 *goodix_proto_build_message (guint8 category,
+ guint8 command,
+ const guint8 *payload,
+ gsize payload_len,
+ gboolean use_checksum,
+ gsize *out_len);
+
+gboolean goodix_proto_validate_checksum (const guint8 *data,
+ gsize len);
+
+void goodix_proto_rx_reset (GoodixReassembly *rx);
+gboolean goodix_proto_rx_feed_chunk (GoodixReassembly *rx,
+ const guint8 *chunk,
+ gsize chunk_len);
+gboolean goodix_proto_rx_complete (GoodixReassembly *rx);
+
+/* out_payload points into the reassembly buffer — it is only valid until the
+ * next receive reset. */
+gboolean goodix_proto_rx_parse (GoodixReassembly *rx,
+ guint8 *out_category,
+ guint8 *out_command,
+ const guint8 **out_payload,
+ gsize *out_payload_len);
+
+void goodix_proto_build_mcu_message (guint32 data_type,
+ const guint8 *data,
+ gsize data_len,
+ guint8 **out_payload,
+ gsize *out_payload_len);
+
+gboolean goodix_proto_parse_mcu_message (const guint8 *payload,
+ gsize payload_len,
+ guint32 expected_type,
+ const guint8 **out_data,
+ gsize *out_data_len);
+
+gboolean goodix_proto_parse_production_read (const guint8 *payload,
+ gsize payload_len,
+ guint32 expected_type,
+ const guint8 **out_data,
+ gsize *out_data_len);
diff --git a/libfprint/drivers/goodix53x5/device/scan.c b/libfprint/drivers/goodix53x5/device/scan.c
new file mode 100644
index 0000000..c0ae1bf
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/scan.c
@@ -0,0 +1,1496 @@
+/*
+ * Goodix 53x5 driver for libfprint — Scan flow (FDT finger detection and capture)
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/transport.h"
+#include "device/commands.h"
+#include "device/calibration.h"
+#include "device/image.h"
+#include "device/base.h"
+#include "device/scan.h"
+#include "device/session.h"
+
+#include <string.h>
+
+typedef enum {
+ GOODIX_SCAN_COORD_ENSURE_REFERENCE = 0,
+ GOODIX_SCAN_COORD_ENSURE_REFERENCE_DONE,
+ GOODIX_SCAN_COORD_POWER_ON,
+ GOODIX_SCAN_COORD_ARM_DOWN,
+ GOODIX_SCAN_COORD_WAIT_EVENT,
+ GOODIX_SCAN_COORD_DISPATCH_EVENT,
+ GOODIX_SCAN_COORD_DOWN_MANUAL,
+ GOODIX_SCAN_COORD_DOWN_VALIDATE,
+ GOODIX_SCAN_COORD_CAPTURE,
+ GOODIX_SCAN_COORD_ARM_UP,
+ GOODIX_SCAN_COORD_ARM_UP_DONE,
+ GOODIX_SCAN_COORD_RECOVERY_ARM_UP,
+ GOODIX_SCAN_COORD_RECOVERY_ARM_UP_DONE,
+ GOODIX_SCAN_COORD_REFRESH,
+ GOODIX_SCAN_COORD_REFRESH_DONE,
+ GOODIX_SCAN_COORD_UP_HEALTH,
+ GOODIX_SCAN_COORD_REARM_DOWN,
+ GOODIX_SCAN_COORD_REARM_DOWN_DONE,
+ GOODIX_SCAN_COORD_RESTORE_CONFIG,
+ GOODIX_SCAN_COORD_RESTORE_LOST_CONFIG,
+ GOODIX_SCAN_COORD_ESD,
+ GOODIX_SCAN_COORD_ESD_DONE,
+ GOODIX_SCAN_COORD_CHANNEL_REARM,
+ GOODIX_SCAN_COORD_CHANNEL_REARM_DONE,
+ GOODIX_SCAN_COORD_DEACTIVATE_EC,
+ GOODIX_SCAN_COORD_DEACTIVATE_EC_DONE,
+ GOODIX_SCAN_COORD_WAIT_CPU,
+ GOODIX_SCAN_COORD_CYCLE_SETTLED,
+ GOODIX_SCAN_COORD_CLEANUP_JOIN,
+ GOODIX_SCAN_COORD_CLEANUP_HEALTH,
+ GOODIX_SCAN_COORD_CLEANUP_SLEEP,
+ GOODIX_SCAN_COORD_CLEANUP_DONE,
+ GOODIX_SCAN_COORD_NUM_STATES,
+} GoodixScanCoordinatorState;
+
+typedef struct
+{
+ FpiSsm *parent_ssm;
+ FpiSsm *ssm;
+ GoodixScanCaptureReadyCallback capture_ready;
+ GoodixScanCycleSettledCallback cycle_settled;
+ gpointer user_data;
+ GCancellable *action_cancel;
+ gulong action_cancel_id;
+ GoodixFdtEventType event_type;
+ GoodixProfile9FdtRefreshReason refresh_reason;
+ GoodixScanDisposition disposition;
+ GError *stop_error;
+ guint16 prior_down[GOODIX_PROFILE9_FDT_AREA_COUNT];
+ gboolean waiting_event;
+ gboolean dispatching;
+ gboolean stop_requested;
+ gboolean cpu_done;
+ gboolean cpu_outstanding;
+ gboolean refresh_deferred;
+ gboolean cycle_active;
+ gboolean recovering_generation;
+ gboolean release_settled;
+ gboolean idle;
+ /* The action already received its outcome; the rest is maintenance. */
+ gboolean detached;
+ FpiSsm *health_parent;
+ GSource *health_timer;
+ FpDevice *service_device;
+} GoodixScanCoordinatorData;
+
+static void goodix_scan_coordinator_handler (FpiSsm *ssm,
+ FpDevice *dev);
+static void goodix_scan_start_capture_subsm (FpiSsm *parent_ssm,
+ FpDevice *dev);
+static void goodix_scan_start_health_wait (FpiSsm *parent,
+ FpDevice *dev);
+static void goodix_scan_detach_action (FpiSsm *ssm,
+ FpDevice *dev);
+
+/* usbinterface!0115a4 owns four module-static history words. HAL sensor
+ * checking reseeds current/default only; neither close nor reset clears them.
+ * Serialize the shared words if different device main contexts run in parallel. */
+static GMutex goodix_dac_history_lock;
+static GoodixDynamicDacState goodix_dac_history;
+
+static void
+goodix_scan_coordinator_data_free (GoodixScanCoordinatorData *data)
+{
+ if (!data)
+ return;
+
+ if (data->action_cancel && data->action_cancel_id)
+ g_cancellable_disconnect (data->action_cancel, data->action_cancel_id);
+ g_clear_object (&data->action_cancel);
+ g_clear_error (&data->stop_error);
+ g_clear_pointer (&data->health_timer, g_source_destroy);
+ g_clear_object (&data->service_device);
+ g_free (data);
+}
+
+static void
+goodix_scan_normalize_event (const GoodixProfile9FdtEvent *event,
+ guint16 values[GOODIX_PROFILE9_FDT_AREA_COUNT])
+{
+ for (guint i = 0; i < GOODIX_PROFILE9_FDT_AREA_COUNT; i++)
+ {
+ guint16 raw = event->raw[i * 2] |
+ ((guint16) event->raw[i * 2 + 1] << 8);
+
+ values[i] = raw >> 1;
+ }
+}
+
+static gboolean
+goodix_scan_majority_changed (const guint16 first[GOODIX_PROFILE9_FDT_AREA_COUNT],
+ const guint16 second[GOODIX_PROFILE9_FDT_AREA_COUNT],
+ guint16 threshold)
+{
+ guint changed = 0;
+
+ for (guint i = 0; i < GOODIX_PROFILE9_FDT_AREA_COUNT; i++)
+ changed += ABS ((gint) first[i] - (gint) second[i]) > threshold;
+
+ return changed > GOODIX_PROFILE9_FDT_AREA_COUNT / 2;
+}
+
+static gboolean
+goodix_scan_all_strictly_close (const guint16 first[GOODIX_PROFILE9_FDT_AREA_COUNT],
+ const guint16 second[GOODIX_PROFILE9_FDT_AREA_COUNT],
+ guint16 threshold)
+{
+ for (guint i = 0; i < GOODIX_PROFILE9_FDT_AREA_COUNT; i++)
+ if (ABS ((gint) first[i] - (gint) second[i]) >= threshold)
+ return FALSE;
+
+ return TRUE;
+}
+
+static gboolean
+goodix_scan_apply_anchor (FpiDeviceGoodix53x5 *self,
+ const guint16 current[GOODIX_PROFILE9_FDT_AREA_COUNT],
+ gboolean seed_if_empty)
+{
+ GoodixProfile9FdtState *fdt = &self->profile9_fdt;
+
+ if (fdt->drift_anchor_empty)
+ {
+ if (seed_if_empty)
+ {
+ memcpy (fdt->drift_anchor, current, sizeof (fdt->drift_anchor));
+ fdt->drift_anchor_empty = FALSE;
+ }
+ return FALSE;
+ }
+
+ if (goodix_scan_majority_changed (fdt->drift_anchor, current,
+ self->calib.delta_down))
+ return TRUE;
+
+ if (goodix_scan_all_strictly_close (fdt->drift_anchor, current,
+ self->calib.delta_down / 3))
+ {
+ memset (fdt->drift_anchor, 0, sizeof (fdt->drift_anchor));
+ fdt->drift_anchor_empty = TRUE;
+ }
+
+ return FALSE;
+}
+
+static gboolean
+goodix_scan_disposition_waits_for_up (GoodixScanDisposition disposition)
+{
+ return disposition == GOODIX_SCAN_DISPOSITION_AUTH_RETRY_AFTER_UP ||
+ disposition == GOODIX_SCAN_DISPOSITION_ENROLL_CONTINUE_AFTER_UP ||
+ disposition == GOODIX_SCAN_DISPOSITION_ENROLL_FINAL_AFTER_UP;
+}
+
+static void
+goodix_scan_finish_requested (GoodixScanCoordinatorData *data)
+{
+ if (data->stop_error)
+ fpi_ssm_mark_failed (data->ssm, g_steal_pointer (&data->stop_error));
+ else
+ fpi_ssm_mark_completed (data->ssm);
+}
+
+static void
+goodix_scan_maybe_finish_requested (GoodixScanCoordinatorData *data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (
+ fpi_ssm_get_device (data->ssm));
+
+ if (self->profile9_fdt.owner != data->ssm ||
+ data->dispatching || data->waiting_event || self->transport)
+ return;
+ if (data->cpu_outstanding)
+ {
+ if (fpi_ssm_get_cur_state (data->ssm) <
+ GOODIX_SCAN_COORD_CLEANUP_JOIN &&
+ fpi_ssm_get_cur_state (data->ssm) != GOODIX_SCAN_COORD_WAIT_CPU)
+ fpi_ssm_jump_to_state (data->ssm, GOODIX_SCAN_COORD_WAIT_CPU);
+ return;
+ }
+ if (data->refresh_deferred)
+ {
+ data->refresh_deferred = FALSE;
+ data->dispatching = TRUE;
+ fpi_ssm_jump_to_state (data->ssm, GOODIX_SCAN_COORD_REFRESH);
+ return;
+ }
+ goodix_scan_finish_requested (data);
+}
+
+static void
+goodix_scan_request_stop (GoodixScanCoordinatorData *data,
+ GError *error)
+{
+ FpDevice *dev = fpi_ssm_get_device (data->ssm);
+
+ if (data->stop_requested)
+ {
+ if (error && !data->stop_error)
+ data->stop_error = error;
+ else
+ g_clear_error (&error);
+ goodix_scan_maybe_finish_requested (data);
+ return;
+ }
+
+ data->stop_requested = TRUE;
+ data->stop_error = error;
+
+ if (data->waiting_event && !data->dispatching)
+ {
+ goodix_transport_cancel_event (dev);
+ return;
+ }
+
+ goodix_scan_maybe_finish_requested (data);
+}
+
+static void
+goodix_scan_action_cancelled (GCancellable *cancellable,
+ gpointer user_data)
+{
+ GoodixScanCoordinatorData *data = user_data;
+
+ (void) cancellable;
+ goodix_scan_request_stop (
+ data, g_error_new_literal (G_IO_ERROR, G_IO_ERROR_CANCELLED,
+ "Profile-9 scan action cancelled"));
+}
+
+static void
+goodix_scan_gtls_restarted (FpDevice *dev, GError *error, gpointer user_data)
+{
+ GoodixScanCoordinatorData *data = user_data;
+
+ data->dispatching = FALSE;
+ if (error)
+ {
+ goodix_scan_request_stop (data, error);
+ return;
+ }
+ /* Only a reconnect the sensor asked for arms afterwards, as the vendor's
+ * handler does, even while the scan stops. A restart after a failed image
+ * read only restarts the channel: the capture's failure path arms after it. */
+ if (FPI_DEVICE_GOODIX53X5 (dev)->reconnect_requested)
+ {
+ data->dispatching = TRUE;
+ fpi_ssm_jump_to_state (data->ssm, GOODIX_SCAN_COORD_CHANNEL_REARM);
+ return;
+ }
+ fpi_ssm_jump_to_state (data->ssm, GOODIX_SCAN_COORD_WAIT_EVENT);
+}
+
+static void
+goodix_scan_restarted_before_arm (FpDevice *dev, GError *error, gpointer user_data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ FpiSsm *ssm = user_data;
+ gboolean reconnect = self->reconnect_requested;
+
+ if (error)
+ fpi_ssm_mark_failed (ssm, error);
+ else
+ fpi_ssm_jump_to_state (ssm, reconnect &&
+ fpi_ssm_get_cur_state (ssm) == GOODIX_SCAN_COORD_RECOVERY_ARM_UP ?
+ GOODIX_SCAN_COORD_CHANNEL_REARM : fpi_ssm_get_cur_state (ssm));
+}
+
+/* Serialize a pending restart before arming on the replacement session.
+ * D0 selects its own down-arm; a failed read keeps the capture continuation.
+ * Inert for 53x5: it requests no reconnects and its restarts do not disarm. */
+static gboolean
+goodix_scan_restart_before_arm (FpiSsm *ssm, FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (self->reconnect_requested)
+ {
+ self->reconnect_requested = FALSE;
+ return FALSE;
+ }
+ if (!self->gtls_restart_pending || !goodix_family (self)->channel.restart_disarms)
+ return FALSE;
+ goodix_start_gtls_restart (dev, goodix_scan_restarted_before_arm, ssm);
+ return TRUE;
+}
+
+static void
+goodix_scan_event_done (FpDevice *dev, const GoodixTransportResult *result,
+ GError *error, gpointer user_data)
+{
+ GoodixScanCoordinatorData *data = user_data;
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ data->waiting_event = FALSE;
+ if (!error && result->restart_gtls)
+ {
+ /* Keep the coordinator alive through asynchronous recovery and cancellation.
+ * One transport owner serializes GTLS with capture and arm commands. */
+ data->dispatching = TRUE;
+ goodix_start_gtls_restart (dev, goodix_scan_gtls_restarted, data);
+ return;
+ }
+ if (!error && self->config_restore_pending && !self->pending_fdt.event.pending)
+ {
+ /* Woken by a configuration loss: restore it before waiting again. */
+ fpi_ssm_jump_to_state (data->ssm, GOODIX_SCAN_COORD_WAIT_EVENT);
+ return;
+ }
+ if (!error)
+ {
+ /* Selected work must still dispatch if its packet won cancellation. */
+ data->dispatching = TRUE;
+ fpi_ssm_next_state (data->ssm);
+ return;
+ }
+ if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED) &&
+ !g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_CANCELLED))
+ {
+ if (error->domain == G_USB_DEVICE_ERROR || error->domain == G_IO_ERROR)
+ self->needs_reinit = TRUE;
+ fpi_ssm_mark_failed (data->ssm, error);
+ return;
+ }
+ g_clear_error (&error);
+
+ if (!data->stop_requested)
+ {
+ data->stop_requested = TRUE;
+ data->stop_error = fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_GENERAL,
+ "Profile-9 event receive was cancelled unexpectedly");
+ }
+ goodix_scan_maybe_finish_requested (data);
+}
+
+static void
+goodix_scan_prepare_refresh (FpiSsm *ssm,
+ FpiDeviceGoodix53x5 *self,
+ GoodixScanCoordinatorData *data,
+ GoodixProfile9FdtRefreshReason reason)
+{
+ data->refresh_reason = reason;
+ self->profile9_fdt.base_valid = FALSE;
+ if (data->cpu_outstanding)
+ {
+ data->refresh_deferred = TRUE;
+ data->dispatching = FALSE;
+ /* Serialize replacement with the previous immutable CPU input. The
+ * retained native wait state changes only on arm/deactivation. */
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_WAIT_CPU);
+ }
+ else
+ {
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_REFRESH);
+ }
+}
+
+static void
+goodix_scan_config_restored (FpiSsm *ssm, FpDevice *dev, guint8 status,
+ gboolean native_zero, GError *error)
+{
+ /* usbinterface!180015710 discards mode-4 failure before down-arm. Keep
+ * terminal host errors on the existing joined cleanup path. */
+ if (error && !native_zero)
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+ g_clear_error (&error);
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_REARM_DOWN);
+}
+
+/* Returns the scan to waiting once a download of the lost configuration
+ * ends, arming nothing, as the vendor's power-lost handler does. Fails the
+ * scan on an error other than an ordinary command failure. */
+static void
+goodix_scan_lost_config_restored (FpiSsm *ssm, FpDevice *dev, guint8 status,
+ gboolean native_zero, GError *error)
+{
+ GoodixScanCoordinatorData *data = fpi_ssm_get_data (ssm);
+
+ FPI_DEVICE_GOODIX53X5 (dev)->config_restore_active = FALSE;
+ if (error && !native_zero)
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+ if (error)
+ fp_warn ("Restoring the lost configuration failed: %s", error->message);
+ g_clear_error (&error);
+ data->dispatching = FALSE;
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_WAIT_EVENT);
+}
+
+static void
+goodix_scan_manual_done (FpiSsm *ssm, FpDevice *dev, guint8 status,
+ gboolean native_zero, GError *error)
+{
+ GoodixScanCoordinatorData *data = fpi_ssm_get_data (ssm);
+
+ if (error && native_zero)
+ {
+ /* A failed manual read returns from Down_procedure without an arm. */
+ g_clear_error (&error);
+ data->dispatching = FALSE;
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_WAIT_EVENT);
+ }
+ else if (error)
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ }
+ else
+ {
+ fpi_ssm_next_state (ssm);
+ }
+}
+
+static void
+goodix_scan_health_done (FpDevice *dev,
+ const GoodixHealthMeasurement *measurement,
+ GError *error, gpointer user_data)
+{
+ FpiSsm *ssm = user_data;
+
+ if (error)
+ fpi_ssm_mark_failed (ssm, error);
+ else
+ fpi_ssm_next_state (ssm);
+}
+
+static void
+goodix_scan_coordinator_handler (FpiSsm *ssm,
+ FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixProfile9FdtState *fdt = &self->profile9_fdt;
+ GoodixScanCoordinatorData *data = fpi_ssm_get_data (ssm);
+
+ if (fpi_ssm_get_cur_state (ssm) < GOODIX_SCAN_COORD_CLEANUP_JOIN &&
+ fpi_ssm_get_cur_state (ssm) != GOODIX_SCAN_COORD_WAIT_EVENT &&
+ data->stop_requested && !data->dispatching && !data->waiting_event)
+ {
+ goodix_scan_maybe_finish_requested (data);
+ return;
+ }
+
+ switch (fpi_ssm_get_cur_state (ssm))
+ {
+ case GOODIX_SCAN_COORD_ENSURE_REFERENCE:
+ if (data->idle)
+ {
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_WAIT_EVENT);
+ break;
+ }
+ if (self->milan_generation || fdt->initial_recovery_pending)
+ fpi_ssm_next_state (ssm);
+ else
+ goodix_milan_base_start_ensure_subsm (ssm, dev, TRUE);
+ break;
+
+ case GOODIX_SCAN_COORD_ENSURE_REFERENCE_DONE:
+ if (self->milan_generation)
+ {
+ fpi_ssm_next_state (ssm);
+ break;
+ }
+ if (!fdt->initial_recovery_pending)
+ {
+ fpi_ssm_mark_failed (
+ ssm, fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_GENERAL,
+ "Milan reference acquisition produced no generation or recovery state"));
+ return;
+ }
+
+ data->recovering_generation = TRUE;
+ if (fdt->event.pending)
+ {
+ if ((fdt->event.touch_flag & 0x0fff) != 0)
+ fpi_device_report_finger_status_changes (
+ dev, FP_FINGER_STATUS_PRESENT, FP_FINGER_STATUS_NEEDED);
+ else
+ fpi_device_report_finger_status_changes (
+ dev, FP_FINGER_STATUS_NEEDED, FP_FINGER_STATUS_PRESENT);
+ }
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_SCAN_COORD_POWER_ON:
+ fpi_device_report_finger_status_changes (dev, FP_FINGER_STATUS_NEEDED,
+ FP_FINGER_STATUS_PRESENT);
+ goodix_cmd_ec_control (ssm, dev, TRUE);
+ break;
+
+ case GOODIX_SCAN_COORD_ARM_DOWN:
+ if (goodix_scan_restart_before_arm (ssm, dev))
+ return;
+ fdt->wait_mode = GOODIX_PROFILE9_FDT_WAIT_DOWN;
+ goodix_cmd_fdt_down_setup (ssm, dev, fdt->base_down);
+ break;
+
+ case GOODIX_SCAN_COORD_WAIT_EVENT:
+ {
+ if (data->health_parent && goodix_health_is_complete (&self->health))
+ data->stop_requested = TRUE;
+ if (data->idle && data->stop_requested)
+ {
+ /* Join the selected handler, leaving any newer coalesced event
+ * to the next owner rather than extending handoff indefinitely. */
+ data->dispatching = FALSE;
+ goodix_scan_maybe_finish_requested (data);
+ return;
+ }
+ if (self->config_restore_pending && !data->stop_requested)
+ {
+ data->dispatching = TRUE;
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_RESTORE_LOST_CONFIG);
+ return;
+ }
+ /* A pending notification can complete synchronously and free data.
+ * Preserve the arm/stop receive-and-cancel window without borrowing it
+ * after submission. cancel_event affects only a still-pending wait. */
+ gboolean stop = data->stop_requested;
+ data->waiting_event = TRUE;
+ goodix_transport_wait_event (dev, fdt->wait_mode, goodix_scan_event_done, data);
+ if (stop)
+ goodix_transport_cancel_event (dev);
+ }
+ break;
+
+ case GOODIX_SCAN_COORD_DISPATCH_EVENT:
+ {
+ g_autoptr(GError) error = NULL;
+
+ if (!goodix_recv_select_fdt (dev, &data->event_type, &fdt->event,
+ data->prior_down, &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ data->dispatching = TRUE;
+
+ if (data->event_type == GOODIX_FDT_EVENT_ESD)
+ {
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_ESD);
+ return;
+ }
+ if (data->event_type == GOODIX_FDT_EVENT_WAKE)
+ {
+ /* Ordinary screen-on 00dc84 has no requested-mode gate. */
+ fpi_ssm_jump_to_state (ssm, goodix_family (self)->protocol.wake_arm_up (
+ fdt->wait_mode == GOODIX_PROFILE9_FDT_WAIT_UP) ?
+ GOODIX_SCAN_COORD_RECOVERY_ARM_UP :
+ GOODIX_SCAN_COORD_REARM_DOWN);
+ return;
+ }
+ if (data->event_type == GOODIX_FDT_EVENT_DEACTIVATE)
+ {
+ /* Delay belongs to selected work, not to a replaceable timer. */
+ fpi_ssm_jump_to_state_delayed (ssm, GOODIX_SCAN_COORD_DEACTIVATE_EC, 500);
+ return;
+ }
+
+ if (data->event_type == GOODIX_FDT_EVENT_CONFIG)
+ {
+ /* Native worker 00e00d tests the persistent requested mode at
+ * selection, not when the parser publishes the notification. */
+ if (self->requested_mode == GOODIX_REQUESTED_MODE_SLEEP)
+ {
+ data->dispatching = FALSE;
+ fdt->event.pending = FALSE;
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_WAIT_EVENT);
+ return;
+ }
+ /* No sample or release was published. Preserve the selected raw
+ * vector, drift/reference state and outstanding CPU ownership. */
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_RESTORE_CONFIG);
+ return;
+ }
+
+ if (data->event_type == GOODIX_FDT_EVENT_DOWN)
+ {
+ goodix_health_note_down (&self->health);
+ fpi_ssm_next_state (ssm);
+ return;
+ }
+
+ {
+ guint16 current[GOODIX_PROFILE9_FDT_AREA_COUNT];
+ gboolean refresh = FALSE;
+
+ goodix_scan_normalize_event (&fdt->event, current);
+ data->release_settled = data->cycle_active;
+
+ if (data->event_type == GOODIX_FDT_EVENT_REVERSE)
+ {
+ if (!fdt->base_valid)
+ {
+ data->refresh_reason = GOODIX_PROFILE9_FDT_REFRESH_INVALID_BASE;
+ refresh = TRUE;
+ }
+ else if (goodix_scan_majority_changed (
+ data->prior_down, current, self->calib.delta_down) ||
+ goodix_scan_apply_anchor (self, current, TRUE))
+ {
+ refresh = TRUE;
+ }
+ }
+ else
+ {
+ if (goodix_scan_apply_anchor (self, current, FALSE))
+ {
+ refresh = TRUE;
+ }
+ else if (!fdt->base_valid)
+ {
+ data->refresh_reason = GOODIX_PROFILE9_FDT_REFRESH_UP_INVALID_BASE;
+ refresh = TRUE;
+ }
+ }
+
+ if (data->recovering_generation)
+ {
+ data->refresh_reason = GOODIX_PROFILE9_FDT_REFRESH_INVALID_BASE;
+ refresh = TRUE;
+ }
+
+ if (refresh)
+ {
+ GoodixProfile9FdtRefreshReason reason = data->refresh_reason;
+
+ if (reason == GOODIX_PROFILE9_FDT_REFRESH_NONE)
+ reason = data->event_type == GOODIX_FDT_EVENT_REVERSE ?
+ GOODIX_PROFILE9_FDT_REFRESH_REVERSE :
+ GOODIX_PROFILE9_FDT_REFRESH_UP;
+ goodix_scan_prepare_refresh (
+ ssm, self, data, reason);
+ return;
+ }
+ data->refresh_reason = GOODIX_PROFILE9_FDT_REFRESH_NONE;
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_UP_HEALTH);
+ }
+ }
+ break;
+
+ case GOODIX_SCAN_COORD_DOWN_MANUAL:
+ goodix_cmd_fdt_manual_result (ssm, dev, FALSE, fdt->base_manual,
+ goodix_scan_manual_done);
+ break;
+
+ case GOODIX_SCAN_COORD_DOWN_VALIDATE:
+ {
+ g_autoptr(GError) error = NULL;
+ const guint8 *payload;
+ gsize payload_len;
+
+ if (!goodix_cmd_parse_fdt_manual_reply (dev, &payload, &payload_len,
+ &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ if (goodix_device_is_fdt_base_valid (fdt->event.raw, payload + 4,
+ GOODIX_FDT_BASE_LEN,
+ self->calib.delta_fdt))
+ {
+ goodix_scan_prepare_refresh (
+ ssm, self, data, GOODIX_PROFILE9_FDT_REFRESH_FALSE_DOWN);
+ return;
+ }
+
+ if (self->requested_mode != GOODIX_REQUESTED_MODE_CAPTURE ||
+ !self->capture_callback_pending || data->cycle_active)
+ {
+ /* Native manual validation precedes the live-request gate. A
+ * genuine inactive down still arms up, but never captures. */
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_RECOVERY_ARM_UP);
+ return;
+ }
+ fpi_device_report_finger_status_changes (dev, FP_FINGER_STATUS_PRESENT,
+ FP_FINGER_STATUS_NEEDED);
+ if (!self->hardware_reference)
+ {
+ data->recovering_generation = TRUE;
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_RECOVERY_ARM_UP);
+ return;
+ }
+ fpi_ssm_next_state (ssm);
+ }
+ break;
+
+ case GOODIX_SCAN_COORD_CAPTURE:
+ goodix_scan_start_capture_subsm (ssm, dev);
+ break;
+
+ case GOODIX_SCAN_COORD_ARM_UP:
+ self->capture_callback_pending = FALSE;
+ data->cycle_active = TRUE;
+ data->release_settled = FALSE;
+ data->cpu_done = FALSE;
+ if (!data->stop_requested && !data->idle)
+ {
+ if (!self->milan_generation || !self->captured_raw_image)
+ {
+ data->recovering_generation = TRUE;
+ }
+ else
+ {
+ /* Deliver the completed frame before up-arm. Dispatch ownership
+ * holds the coordinator until the command finishes; cleanup joins
+ * any worker even if that command fails. */
+ data->cpu_outstanding = TRUE;
+ goodix_milan_generation_prepare_setup (dev, self->milan_generation);
+ GOODIX53X5_DEBUG_ONLY (
+ guint64 use = goodix_milan_generation_note_use (self->milan_generation);
+
+ fp_info ("Using Milan generation id=%" G_GUINT64_FORMAT
+ " use=%" G_GUINT64_FORMAT,
+ self->milan_generation->generation_id, use);
+ )
+ data->capture_ready (dev, data->user_data);
+ }
+ }
+ /* Hardware callback invocation consumes the marker even if cancellation
+ * suppressed engine/CPU delivery. No setup is initialized for that case. */
+ self->hardware_refresh_pending = FALSE;
+ fdt->wait_mode = GOODIX_PROFILE9_FDT_WAIT_UP;
+ goodix_cmd_fdt_up_setup (ssm, dev, fdt->base_up);
+ break;
+
+ case GOODIX_SCAN_COORD_ARM_UP_DONE:
+ case GOODIX_SCAN_COORD_RECOVERY_ARM_UP_DONE:
+ data->dispatching = FALSE;
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_WAIT_EVENT);
+ break;
+
+ case GOODIX_SCAN_COORD_RECOVERY_ARM_UP:
+ data->dispatching = TRUE;
+ if (goodix_scan_restart_before_arm (ssm, dev))
+ return;
+ fdt->wait_mode = GOODIX_PROFILE9_FDT_WAIT_UP;
+ goodix_cmd_fdt_up_setup (ssm, dev, fdt->base_up);
+ break;
+
+ case GOODIX_SCAN_COORD_REFRESH:
+ goodix_milan_base_start_forced_refresh_subsm (ssm, dev,
+ data->refresh_reason);
+ break;
+
+ case GOODIX_SCAN_COORD_REFRESH_DONE:
+ /* Rejected reverse drift restores only the down base from the selected
+ * event. Newer notifications remain separately owned by pending_fdt. */
+ if (data->refresh_reason == GOODIX_PROFILE9_FDT_REFRESH_REVERSE &&
+ !fdt->base_valid)
+ goodix_device_generate_fdt_base (fdt->event.raw, GOODIX_FDT_BASE_LEN,
+ fdt->base_down);
+ data->refresh_reason = GOODIX_PROFILE9_FDT_REFRESH_NONE;
+ if (self->milan_generation)
+ data->recovering_generation = FALSE;
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_SCAN_COORD_REARM_DOWN:
+ if (goodix_scan_restart_before_arm (ssm, dev))
+ return;
+ fdt->wait_mode = GOODIX_PROFILE9_FDT_WAIT_DOWN;
+ goodix_cmd_fdt_down_setup (ssm, dev, fdt->base_down);
+ break;
+
+ case GOODIX_SCAN_COORD_UP_HEALTH:
+ /* Health runs for event_type == UP with a retained hardware_reference,
+ * after reference handling (including rejection/failure), before down
+ * arm. Neither base_valid nor an active user request gates eligibility;
+ * DOWN/REVERSE continuations passing this state do not run UP health. */
+ if (data->event_type == GOODIX_FDT_EVENT_UP && self->hardware_reference)
+ goodix_health_start_pair (dev, GOODIX_HEALTH_PAIR_UP,
+ goodix_scan_health_done, ssm);
+ else
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_SCAN_COORD_REARM_DOWN_DONE:
+ data->dispatching = FALSE;
+ fdt->event.pending = FALSE;
+
+ if (self->pending_fdt.event.pending || data->stop_requested)
+ {
+ /* An event already received during rearm precedes CPU settlement.
+ * Otherwise resolve the outstanding arm before shutdown as usual. */
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_WAIT_EVENT);
+ return;
+ }
+ if (data->release_settled)
+ {
+ fpi_device_report_finger_status_changes (
+ dev, FP_FINGER_STATUS_NONE,
+ FP_FINGER_STATUS_PRESENT | FP_FINGER_STATUS_NEEDED);
+ if (data->cpu_done)
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_CYCLE_SETTLED);
+ else
+ /* The down arm is one-shot: wait for CPU before posting the
+ * next receive instead of posting one only to cancel it. */
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_WAIT_CPU);
+ return;
+ }
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_WAIT_EVENT);
+ break;
+
+ case GOODIX_SCAN_COORD_WAIT_CPU:
+ break;
+
+ case GOODIX_SCAN_COORD_RESTORE_CONFIG:
+ goodix_cmd_restore_config (ssm, dev, goodix_scan_config_restored);
+ break;
+
+ case GOODIX_SCAN_COORD_RESTORE_LOST_CONFIG:
+ self->config_restore_pending = FALSE;
+ self->config_restore_active = TRUE;
+ goodix_cmd_restore_config (ssm, dev, goodix_scan_lost_config_restored);
+ break;
+
+ case GOODIX_SCAN_COORD_ESD:
+ goodix_cmd_repair_esd (ssm, dev);
+ break;
+
+ case GOODIX_SCAN_COORD_DEACTIVATE_EC:
+ goodix_cmd_ec_control (ssm, dev, FALSE);
+ break;
+
+ case GOODIX_SCAN_COORD_CHANNEL_REARM:
+ /* A reconnect the sensor asked for arms finger-down whatever the scan
+ * waited for, as the vendor's handler does. */
+ self->reconnect_requested = FALSE;
+ fdt->wait_mode = GOODIX_PROFILE9_FDT_WAIT_DOWN;
+ goodix_cmd_fdt_down_setup (ssm, dev, fdt->base_down);
+ break;
+
+ case GOODIX_SCAN_COORD_ESD_DONE:
+ case GOODIX_SCAN_COORD_CHANNEL_REARM_DONE:
+ case GOODIX_SCAN_COORD_DEACTIVATE_EC_DONE:
+ data->dispatching = FALSE;
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_WAIT_EVENT);
+ break;
+
+ case GOODIX_SCAN_COORD_CYCLE_SETTLED:
+ if (data->cycle_settled)
+ data->cycle_settled (dev, data->disposition, data->user_data);
+ if (data->stop_requested)
+ return;
+
+ if (data->disposition == GOODIX_SCAN_DISPOSITION_ENROLL_CONTINUE_AFTER_UP)
+ {
+ data->cycle_active = FALSE;
+ data->release_settled = FALSE;
+ data->cpu_done = FALSE;
+ self->capture_unread = 2;
+ goodix_health_note_capture (&self->health, TRUE);
+ self->capture_callback_pending = TRUE;
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_WAIT_EVENT);
+ }
+ else
+ {
+ fpi_ssm_mark_completed (ssm);
+ }
+ break;
+
+ case GOODIX_SCAN_COORD_CLEANUP_JOIN:
+ fdt->lifecycle = GOODIX_PROFILE9_FDT_LIFECYCLE_STOPPING;
+ if (data->idle)
+ {
+ /* Handoff is not native deactivation. Keep arm state and pending
+ * notification; terminal power policy is owned by the session. */
+ fpi_ssm_jump_to_state (ssm, GOODIX_SCAN_COORD_NUM_STATES);
+ break;
+ }
+ if (data->cpu_outstanding)
+ {
+ if (data->action_cancel &&
+ !g_cancellable_is_cancelled (data->action_cancel))
+ g_cancellable_cancel (data->action_cancel);
+ break;
+ }
+ goodix_scan_detach_action (ssm, dev);
+ break;
+
+ case GOODIX_SCAN_COORD_CLEANUP_HEALTH:
+ /* Native deactivation publishes 0x15 once, replacing only unselected
+ * work. A newer FDT/notice during sleep replaces it in turn. The service
+ * selects surviving work after the foreground joins. */
+ fdt->wait_mode = GOODIX_PROFILE9_FDT_WAIT_NONE;
+ self->pending_fdt.type = GOODIX_FDT_EVENT_DEACTIVATE;
+ self->pending_fdt.event.pending = TRUE;
+ self->capture_callback_pending = FALSE;
+ if (goodix_health_is_complete (&self->health))
+ fpi_ssm_next_state (ssm);
+ else
+ goodix_scan_start_health_wait (ssm, dev);
+ break;
+
+ case GOODIX_SCAN_COORD_CLEANUP_SLEEP:
+ {
+ gboolean study_allowed = goodix_health_finish_deactivation (&self->health);
+
+ fp_dbg ("Deactivation retained study permission: %d", study_allowed);
+ goodix_cmd_set_sleep_mode (ssm, dev);
+ }
+ break;
+
+ case GOODIX_SCAN_COORD_CLEANUP_DONE:
+ if (data->stop_error)
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&data->stop_error));
+ else
+ fpi_ssm_mark_completed (ssm);
+ break;
+
+ case GOODIX_SCAN_COORD_NUM_STATES:
+ g_assert_not_reached ();
+ }
+}
+
+/* The action's outcome is final once its CPU work has joined. Hand it back
+ * now and finish the native deactivation tail (health wait, sleep) as the
+ * session's background owner, so a completed match reports immediately.
+ * Like the native adapter, a hardware failure after the comparison does not
+ * invalidate a positive result; it only marks the session for reconstruction. */
+static void
+goodix_scan_detach_action (FpiSsm *ssm, FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixScanCoordinatorData *data = fpi_ssm_get_data (ssm);
+ FpiSsm *parent = g_steal_pointer (&data->parent_ssm);
+ GError *outcome = g_steal_pointer (&data->stop_error);
+
+ if (!outcome && fpi_ssm_get_error (ssm))
+ outcome = g_error_copy (fpi_ssm_get_error (ssm));
+ if (outcome && !g_error_matches (outcome, G_IO_ERROR, G_IO_ERROR_CANCELLED))
+ {
+ self->needs_reinit = TRUE;
+ if (data->cpu_done &&
+ data->disposition == GOODIX_SCAN_DISPOSITION_AUTH_SUCCESS)
+ g_clear_error (&outcome);
+ }
+
+ data->detached = TRUE;
+ goodix_session_detach_action (dev);
+ /* Advance before completing the action: its callback may admit the next
+ * action, which joins this owner through the ordinary stop request. */
+ fpi_ssm_mark_completed (ssm);
+ if (outcome)
+ fpi_ssm_mark_failed (parent, outcome);
+ else
+ fpi_ssm_next_state (parent);
+}
+
+static void
+goodix_scan_coordinator_done (FpiSsm *ssm,
+ FpDevice *dev,
+ GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixScanCoordinatorData *data = fpi_ssm_get_data (ssm);
+
+ g_assert (self->profile9_fdt.owner == ssm);
+ self->profile9_fdt.owner = NULL;
+ self->profile9_fdt.lifecycle = GOODIX_PROFILE9_FDT_LIFECYCLE_STOPPED;
+ if (data->health_parent)
+ {
+ GoodixScanCoordinatorData *parent = fpi_ssm_get_data (data->health_parent);
+
+ g_clear_pointer (&parent->health_timer, g_source_destroy);
+ self->profile9_fdt.owner = data->health_parent;
+ self->profile9_fdt.lifecycle = GOODIX_PROFILE9_FDT_LIFECYCLE_STOPPING;
+ if (error)
+ fpi_ssm_mark_failed (data->health_parent, error);
+ else
+ fpi_ssm_next_state (data->health_parent);
+ return;
+ }
+ if (data->detached)
+ {
+ /* Reconstruction already owns known failures. Let the session classify
+ * any remaining tail error without changing the delivered result. */
+ if (self->needs_reinit)
+ g_clear_error (&error);
+ goodix_session_service_done (dev, error);
+ return;
+ }
+ /* Every action-owned coordinator passes through CLEANUP_JOIN and detaches. */
+ g_assert (data->idle);
+ goodix_session_service_done (dev, error);
+}
+
+static void
+goodix_scan_health_wait_expired (FpDevice *dev, gpointer user_data)
+{
+ GoodixScanCoordinatorData *parent = user_data;
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ parent->health_timer = NULL;
+ /* Stop selection, but join a selected pair/refresh/500-ms EC handler. */
+ goodix_scan_request_stop (fpi_ssm_get_data (self->profile9_fdt.owner), NULL);
+}
+
+static void
+goodix_scan_start_health_wait (FpiSsm *parent_ssm, FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixScanCoordinatorData *parent = fpi_ssm_get_data (parent_ssm);
+ GoodixScanCoordinatorData *data = g_new0 (GoodixScanCoordinatorData, 1);
+ FpiSsm *ssm;
+
+ /* Native deactivation waits while the independent event worker continues.
+ * Lend hardware ownership to a maintenance-only child for that bounded wait.
+ * The single coalescing slot also owns 0x15; no extra EC timer is introduced. */
+ data->idle = TRUE;
+ data->health_parent = parent_ssm;
+ ssm = fpi_ssm_new_full (dev, goodix_scan_coordinator_handler,
+ GOODIX_SCAN_COORD_NUM_STATES,
+ GOODIX_SCAN_COORD_CLEANUP_JOIN,
+ "goodix-profile9-health-wait");
+ data->ssm = ssm;
+ fpi_ssm_set_data (ssm, data,
+ (GDestroyNotify) goodix_scan_coordinator_data_free);
+ parent->health_timer = fpi_device_add_timeout (
+ dev, GOODIX_HEALTH_DEACTIVATE_TIMEOUT_MS,
+ goodix_scan_health_wait_expired, parent, NULL);
+ self->profile9_fdt.owner = ssm;
+ self->profile9_fdt.lifecycle = GOODIX_PROFILE9_FDT_LIFECYCLE_ACTIVE;
+ fpi_ssm_start (ssm, goodix_scan_coordinator_done);
+}
+
+void
+goodix_scan_start_service (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixScanCoordinatorData *data = g_new0 (GoodixScanCoordinatorData, 1);
+ FpiSsm *ssm;
+
+ g_assert (!self->profile9_fdt.owner && !self->transport);
+ data->idle = TRUE;
+ data->service_device = g_object_ref (dev);
+ ssm = fpi_ssm_new_full (dev, goodix_scan_coordinator_handler,
+ GOODIX_SCAN_COORD_NUM_STATES,
+ GOODIX_SCAN_COORD_CLEANUP_JOIN,
+ "goodix-profile9-service");
+ data->ssm = ssm;
+ fpi_ssm_set_data (ssm, data,
+ (GDestroyNotify) goodix_scan_coordinator_data_free);
+ self->service_active = TRUE;
+ self->profile9_fdt.owner = ssm;
+ self->profile9_fdt.lifecycle = GOODIX_PROFILE9_FDT_LIFECYCLE_ACTIVE;
+ fpi_ssm_start (ssm, goodix_scan_coordinator_done);
+}
+
+void
+goodix_scan_join_service (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ g_assert (self->service_active && self->profile9_fdt.owner);
+ goodix_scan_request_stop (fpi_ssm_get_data (self->profile9_fdt.owner), NULL);
+}
+
+gboolean
+goodix_scan_continue_command_error (FpiSsm *ssm, FpDevice *dev, GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ gint state = fpi_ssm_get_cur_state (ssm);
+
+ if (self->profile9_fdt.owner != ssm ||
+ (state != GOODIX_SCAN_COORD_CLEANUP_SLEEP &&
+ state != GOODIX_SCAN_COORD_DEACTIVATE_EC))
+ return FALSE;
+ fp_dbg ("Continuing after ordinary power command failure: %s", error->message);
+ g_error_free (error);
+ fpi_ssm_next_state (ssm);
+ return TRUE;
+}
+
+void
+goodix_scan_start_coordinator_subsm (
+ FpiSsm *parent_ssm,
+ FpDevice *dev,
+ GoodixScanCaptureReadyCallback capture_ready,
+ GoodixScanCycleSettledCallback cycle_settled,
+ gpointer user_data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixScanCoordinatorData *data;
+ FpiSsm *ssm;
+
+ g_return_if_fail (capture_ready != NULL);
+ if (self->cancel && g_cancellable_is_cancelled (self->cancel))
+ {
+ fpi_ssm_mark_failed (parent_ssm,
+ g_error_new_literal (G_IO_ERROR, G_IO_ERROR_CANCELLED,
+ "Scan cancelled before admission"));
+ return;
+ }
+ if (self->profile9_fdt.owner || self->profile9_fdt.lifecycle !=
+ GOODIX_PROFILE9_FDT_LIFECYCLE_STOPPED)
+ {
+ fpi_ssm_mark_failed (
+ parent_ssm, fpi_device_error_new_msg (FP_DEVICE_ERROR_BUSY,
+ "Profile-9 scan coordinator is already active"));
+ return;
+ }
+
+ data = g_new0 (GoodixScanCoordinatorData, 1);
+ data->parent_ssm = parent_ssm;
+ data->capture_ready = capture_ready;
+ data->cycle_settled = cycle_settled;
+ data->user_data = user_data;
+ data->action_cancel = self->cancel ? g_object_ref (self->cancel) : NULL;
+ ssm = fpi_ssm_new_full (dev, goodix_scan_coordinator_handler,
+ GOODIX_SCAN_COORD_NUM_STATES,
+ GOODIX_SCAN_COORD_CLEANUP_JOIN,
+ "goodix-profile9-scan");
+ data->ssm = ssm;
+ fpi_ssm_set_data (ssm, data,
+ (GDestroyNotify) goodix_scan_coordinator_data_free);
+ self->profile9_fdt.owner = ssm;
+ self->profile9_fdt.lifecycle = GOODIX_PROFILE9_FDT_LIFECYCLE_ACTIVE;
+ /* device_get_data clears HAL +0x1e0 before EC control and initial arming.
+ * Maintenance rearming and configuration repair do not change this mode. */
+ self->requested_mode = GOODIX_REQUESTED_MODE_CAPTURE;
+ /* The previous owner has joined. A new capture supersedes only its
+ * unselected power-off notification; retain real sensor notifications.
+ * Already-selected deactivation finishes before this admission point. */
+ if (self->pending_fdt.event.pending &&
+ self->pending_fdt.type == GOODIX_FDT_EVENT_DEACTIVATE)
+ self->pending_fdt.event.pending = FALSE;
+ self->capture_unread = fpi_device_get_current_action (dev) == FPI_DEVICE_ACTION_ENROLL ? 2 : 1;
+ goodix_health_note_capture (&self->health, self->capture_unread == 2);
+ self->capture_callback_pending = TRUE;
+ fpi_ssm_start (ssm, goodix_scan_coordinator_done);
+ if (self->profile9_fdt.owner == ssm && data->action_cancel)
+ data->action_cancel_id = g_cancellable_connect (
+ data->action_cancel, G_CALLBACK (goodix_scan_action_cancelled), data,
+ NULL);
+}
+
+void
+goodix_scan_set_disposition (FpDevice *dev,
+ GoodixScanDisposition disposition,
+ GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixScanCoordinatorData *data;
+
+ if (!self->profile9_fdt.owner)
+ {
+ fp_warn ("Ignoring disposition for an inactive scan coordinator");
+ g_clear_error (&error);
+ return;
+ }
+
+ data = fpi_ssm_get_data (self->profile9_fdt.owner);
+ if (!data->cycle_active || data->cpu_done || !data->cpu_outstanding)
+ {
+ fp_warn ("Ignoring duplicate scan-cycle disposition");
+ g_clear_error (&error);
+ return;
+ }
+
+ data->cpu_done = TRUE;
+ data->cpu_outstanding = FALSE;
+ data->disposition = disposition;
+ if (fpi_ssm_get_cur_state (data->ssm) >= GOODIX_SCAN_COORD_CLEANUP_JOIN)
+ {
+ /* Cleanup was waiting for this join; the stop reason is already owned. */
+ g_clear_error (&error);
+ goodix_scan_detach_action (data->ssm, dev);
+ return;
+ }
+ if (data->stop_requested)
+ {
+ g_clear_error (&error);
+ goodix_scan_maybe_finish_requested (data);
+ return;
+ }
+ if (disposition == GOODIX_SCAN_DISPOSITION_FATAL)
+ {
+ goodix_scan_request_stop (
+ data, error ? error : fpi_device_error_new (FP_DEVICE_ERROR_GENERAL));
+ }
+ else if (disposition == GOODIX_SCAN_DISPOSITION_CANCELLED)
+ {
+ g_clear_error (&error);
+ goodix_scan_request_stop (
+ data, g_error_new_literal (G_IO_ERROR, G_IO_ERROR_CANCELLED,
+ "Profile-9 scan cycle cancelled"));
+ }
+ else
+ {
+ g_clear_error (&error);
+ if (!goodix_scan_disposition_waits_for_up (disposition))
+ {
+ /* Retain terminal intent while maybe_finish joins a deferred
+ * selected refresh. Its rearm must not require a future release. */
+ goodix_scan_request_stop (data, NULL);
+ }
+ else if (data->refresh_deferred)
+ {
+ data->refresh_deferred = FALSE;
+ data->dispatching = TRUE;
+ fpi_ssm_jump_to_state (data->ssm, GOODIX_SCAN_COORD_REFRESH);
+ }
+ else if (data->release_settled && !data->dispatching &&
+ !data->waiting_event && !self->transport)
+ {
+ fpi_ssm_jump_to_state (data->ssm,
+ GOODIX_SCAN_COORD_CYCLE_SETTLED);
+ }
+ }
+}
+
+void
+goodix_scan_stop_coordinator (FpDevice *dev,
+ GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixScanCoordinatorData *data;
+
+ if (!self->profile9_fdt.owner)
+ {
+ g_clear_error (&error);
+ return;
+ }
+
+ data = fpi_ssm_get_data (self->profile9_fdt.owner);
+ /* The stop can synchronously complete and free the coordinator. */
+ g_autoptr(GCancellable) cancel = data->cpu_outstanding && data->action_cancel ?
+ g_object_ref (data->action_cancel) : NULL;
+ goodix_scan_request_stop (
+ data, error ? error : g_error_new_literal (G_IO_ERROR,
+ G_IO_ERROR_CANCELLED,
+ "Profile-9 scan stopped"));
+ if (cancel)
+ g_cancellable_cancel (cancel);
+}
+
+/* Capture SSM */
+typedef enum {
+ GOODIX_CAPTURE_GET_IMAGE = 0,
+ GOODIX_CAPTURE_DECRYPT,
+ GOODIX_CAPTURE_DECODE,
+ GOODIX_CAPTURE_STORE,
+ GOODIX_CAPTURE_NUM_STATES,
+} GoodixCaptureState;
+
+typedef struct
+{
+ FpiSsm *parent_ssm;
+ gboolean ordinary_failure;
+ guint16 *first_frame;
+} GoodixCaptureData;
+
+static void goodix_capture_ssm_handler (FpiSsm *ssm,
+ FpDevice *dev);
+
+static void
+goodix_capture_data_free (GoodixCaptureData *data)
+{
+ g_free (data->first_frame);
+ g_free (data);
+}
+
+static void
+goodix_capture_command_done (FpiSsm *ssm, FpDevice *dev, guint8 status,
+ gboolean native_zero, GError *error)
+{
+ GoodixCaptureData *data = fpi_ssm_get_data (ssm);
+
+ data->ordinary_failure = error && native_zero;
+ if (error)
+ fpi_ssm_mark_failed (ssm, error);
+ else
+ fpi_ssm_next_state (ssm);
+}
+
+/* ========================================================================
+ * Capture SSM
+ * ======================================================================== */
+
+static void
+goodix_capture_ssm_handler (FpiSsm *ssm,
+ FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ GOODIX53X5_DEBUG_ONLY (gint64 now_us = g_get_monotonic_time ();
+ )
+
+ switch (fpi_ssm_get_cur_state (ssm))
+ {
+ case GOODIX_CAPTURE_GET_IMAGE:
+ {
+ GOODIX53X5_DEBUG_ONLY (
+ self->debug_timing.capture_started_us = now_us;
+ self->debug_timing.capture_phase_started_us = now_us;
+ )
+ /* Live TX-on finger frame */
+ goodix_cmd_request_image_result (ssm, dev, TRUE, TRUE, TRUE,
+ self->calib.dac_h, goodix_capture_command_done);
+ }
+ break;
+
+ case GOODIX_CAPTURE_DECRYPT:
+ {
+ g_autoptr(GError) error = NULL;
+ GoodixCaptureData *data = fpi_ssm_get_data (ssm);
+ g_autofree guint16 *frame = goodix_cmd_dup_image_reply (dev, &error);
+
+ goodix_debug_timing_log (dev, "capture", "get_image",
+ now_us - self->debug_timing.capture_phase_started_us,
+ NULL);
+ GOODIX53X5_DEBUG_ONLY (
+ self->debug_timing.capture_phase_started_us = now_us;
+ )
+
+ if (!frame)
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+
+ /* Command success and raw decode precede adjustment. Receiver arrivals
+ * and base captures do not adjust; metadata sees the post-read DAC. */
+ g_mutex_lock (&goodix_dac_history_lock);
+ goodix_dac_history.default_dac = self->dynamic_dac.default_dac;
+ goodix_device_adjust_dac (&goodix_dac_history, &self->calib,
+ frame,
+ self->hardware_reference);
+ self->dynamic_dac = goodix_dac_history;
+ g_mutex_unlock (&goodix_dac_history_lock);
+
+ /* Each success adjusts before decrement. A failed attempt discards
+ * its first image but retains this count and all DAC/history effects. */
+ self->capture_unread--;
+ if (!data->first_frame)
+ data->first_frame = g_steal_pointer (&frame);
+ if (self->capture_unread)
+ {
+ fpi_ssm_jump_to_state (ssm, GOODIX_CAPTURE_GET_IMAGE);
+ return;
+ }
+
+ GOODIX53X5_DEBUG_ONLY (
+ if (goodix_debug_timing_enabled ())
+ {
+ gint64 done_us = g_get_monotonic_time ();
+
+ goodix_debug_timing_log (dev, "capture", "process",
+ done_us - self->debug_timing.capture_phase_started_us,
+ NULL);
+ if (self->debug_timing.capture_started_us != 0)
+ goodix_debug_timing_log (dev, "capture", "total",
+ done_us - self->debug_timing.capture_started_us,
+ NULL);
+ self->debug_timing.capture_started_us = 0;
+ }
+ )
+
+ fpi_ssm_next_state (ssm);
+ }
+ break;
+
+ case GOODIX_CAPTURE_DECODE:
+ /* Already decoded in previous state, just advance */
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_CAPTURE_STORE:
+ {
+ GoodixCaptureData *data = fpi_ssm_get_data (ssm);
+
+ /* Publish the first frame of this successful attempt with the DAC
+ * produced by its last read. No partial attempt escapes to the CPU. */
+ self->captured_raw_image = g_steal_pointer (&data->first_frame);
+ self->captured_enroll_allowed = goodix_health_enroll_allowed (&self->health);
+ }
+ fpi_ssm_mark_completed (ssm);
+ break;
+ }
+}
+
+static void
+goodix_capture_ssm_done (FpiSsm *ssm,
+ FpDevice *dev,
+ GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixCaptureData *capture = fpi_ssm_get_data (ssm);
+ gboolean read_failed;
+
+ read_failed = error && capture->ordinary_failure;
+ if (!read_failed)
+ {
+ if (error)
+ fpi_ssm_mark_failed (capture->parent_ssm, error);
+ else
+ fpi_ssm_next_state (capture->parent_ssm);
+ return;
+ }
+
+ g_assert (self->profile9_fdt.owner == capture->parent_ssm);
+ g_assert (fpi_ssm_get_cur_state (capture->parent_ssm) ==
+ GOODIX_SCAN_COORD_CAPTURE);
+#ifdef GOODIX53X5_DEBUG
+ self->debug_timing.capture_started_us = 0;
+ self->debug_timing.capture_phase_started_us = 0;
+#endif
+ g_clear_error (&error);
+
+ /* Application cancellation cannot cut short the selected handler's rearm. */
+ fpi_ssm_jump_to_state (capture->parent_ssm,
+ goodix_family (self)->channel.rearm_after_capture (self) ?
+ GOODIX_SCAN_COORD_REARM_DOWN : GOODIX_SCAN_COORD_REARM_DOWN_DONE);
+}
+
+/* ========================================================================
+ * Sub-SSM start wrappers
+ * ======================================================================== */
+
+static void
+goodix_scan_start_capture_subsm (FpiSsm *parent_ssm, FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixCaptureData *data = g_new0 (GoodixCaptureData, 1);
+ FpiSsm *sub = fpi_ssm_new (dev, goodix_capture_ssm_handler,
+ GOODIX_CAPTURE_NUM_STATES);
+
+ data->parent_ssm = parent_ssm;
+#ifdef GOODIX53X5_DEBUG
+ g_clear_pointer (&self->captured_image, g_free);
+#endif
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ g_assert (self->capture_unread > 0);
+ fpi_ssm_set_data (sub, data, (GDestroyNotify) goodix_capture_data_free);
+ fpi_ssm_start (sub, goodix_capture_ssm_done);
+}
diff --git a/libfprint/drivers/goodix53x5/device/scan.h b/libfprint/drivers/goodix53x5/device/scan.h
new file mode 100644
index 0000000..b0b8d34
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/scan.h
@@ -0,0 +1,81 @@
+/*
+ * Goodix 53x5 driver for libfprint — Scan flow (FDT finger detection and capture)
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#pragma once
+
+#include "driver-private.h"
+
+/* Takes an ordinary exhausted command error only when its native continuation
+ * ignores that result. Terminal hardware/host errors never enter this path. */
+gboolean goodix_scan_continue_command_error (FpiSsm *ssm,
+ FpDevice *dev,
+ GError *error);
+
+typedef enum
+{
+ /* Authentication matched; stop without waiting for a later lift event. */
+ GOODIX_SCAN_DISPOSITION_AUTH_SUCCESS = 0,
+ /* Authentication did not match or needs retry; settle the lift first. */
+ GOODIX_SCAN_DISPOSITION_AUTH_RETRY_AFTER_UP,
+ /* Enrollment accepted/rejected one probe and needs another lift-delimited cycle. */
+ GOODIX_SCAN_DISPOSITION_ENROLL_CONTINUE_AFTER_UP,
+ /* Enrollment accepted its final probe; settle the lift, then stop. */
+ GOODIX_SCAN_DISPOSITION_ENROLL_FINAL_AFTER_UP,
+ /* Stop after bounded cleanup and fail with the supplied error. */
+ GOODIX_SCAN_DISPOSITION_FATAL,
+ /* Stop after bounded cleanup with cancellation. */
+ GOODIX_SCAN_DISPOSITION_CANCELLED,
+} GoodixScanDisposition;
+
+typedef void (*GoodixScanCaptureReadyCallback) (FpDevice *dev,
+ gpointer user_data);
+typedef void (*GoodixScanCycleSettledCallback) (
+ FpDevice *dev,
+ GoodixScanDisposition disposition,
+ gpointer user_data);
+
+/* Start the action-scoped profile-9 event coordinator as @parent_ssm's child.
+ * It owns command/event I/O until completion. @capture_ready is invoked only
+ * after capture, up-arm, and submission of the event receive. The action's CPU
+ * callback must return one disposition with goodix_scan_set_disposition().
+ * Enrollment may return ENROLL_CONTINUE repeatedly; @cycle_settled runs after
+ * lift/reverse handling and down rearm, before the next capture cycle. */
+void goodix_scan_start_coordinator_subsm (
+ FpiSsm *parent_ssm,
+ FpDevice *dev,
+ GoodixScanCaptureReadyCallback capture_ready,
+ GoodixScanCycleSettledCallback cycle_settled,
+ gpointer user_data);
+
+/* Transfer @error to the active coordinator. @error is required only for
+ * GOODIX_SCAN_DISPOSITION_FATAL and ignored (and freed) otherwise. */
+void goodix_scan_set_disposition (FpDevice *dev,
+ GoodixScanDisposition disposition,
+ GError *error);
+
+/* Request external cancellation/failure and cancel any outstanding CPU task.
+ * Internal successful stops are requested by returning a disposition instead. */
+void goodix_scan_stop_coordinator (FpDevice *dev,
+ GError *error);
+
+/* Request-independent mode of the same coordinator. Start only after the
+ * preceding logical wait has joined. Stop completes selected work before the
+ * session handoff; it neither captures a live frame nor adds an initial arm. */
+void goodix_scan_start_service (FpDevice *dev);
+void goodix_scan_join_service (FpDevice *dev);
diff --git a/libfprint/drivers/goodix53x5/device/session.c b/libfprint/drivers/goodix53x5/device/session.c
new file mode 100644
index 0000000..6328e9b
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/session.c
@@ -0,0 +1,1548 @@
+/*
+ * Goodix 53x5 driver for libfprint — Device session (open, GTLS, reinit)
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/transport.h"
+#include "device/commands.h"
+#include "device/calibration.h"
+#include "device/base.h"
+#include "device/persistence.h"
+#include "device/scan.h"
+#include "device/session.h"
+#include "device/auth.h"
+#include "device/enroll.h"
+
+#include <string.h>
+#include <openssl/crypto.h>
+
+#define GOODIX_PSK_STATE_FILE "/var/lib/fprint/goodix53x5.psk"
+
+/* ========================================================================
+ * Hardware ownership
+ *
+ * The open session always has at most one hardware owner: background
+ * maintenance (the idle service, or the deactivation tail a completed action
+ * left behind), one foreground action, or the reader join that suspend and
+ * close request. Every owner reports back through goodix_session_settle(),
+ * which then starts whatever is waiting.
+ * ======================================================================== */
+
+GCancellable *
+goodix_session_io_cancellable (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (self->profile9_fdt.owner || self->service_active ||
+ self->suspend_pending || self->session_suspended)
+ return self->session_cancel;
+ return fpi_device_get_cancellable (dev);
+}
+
+static void
+goodix_session_hardware_joined (FpDevice *dev, gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ void (*joined) (FpDevice *, gpointer) = self->service_joined;
+ gpointer joined_data = self->service_joined_data;
+
+ /* Retire the stop owner only after the physical reader's callback joined.
+ * The continuation may start power I/O or complete an outward request. */
+ self->service_joined = NULL;
+ self->service_joined_data = NULL;
+ self->service_draining = FALSE;
+ joined (dev, joined_data);
+}
+
+void
+goodix_session_settle (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ /* Wait for the current owner; it reports back here when it stops. */
+ if (self->foreground_active || self->service_active || self->service_draining)
+ return;
+ if (self->action_pending)
+ {
+ GError *error = NULL;
+
+ self->action_pending = FALSE;
+ if (self->session_suspended || self->suspend_pending)
+ error = fpi_device_error_new_msg (FP_DEVICE_ERROR_BUSY,
+ "Hardware session is suspended");
+ else if (self->service_joined || fpi_device_action_is_cancelled (dev))
+ error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_CANCELLED,
+ "Action cancelled during hardware handoff");
+ if (error)
+ {
+ fpi_device_action_error (dev, error);
+ }
+ else
+ {
+ self->foreground_active = TRUE;
+ if (fpi_device_get_current_action (dev) == FPI_DEVICE_ACTION_ENROLL)
+ goodix_enroll_start (dev);
+ else
+ goodix_auth_start (dev);
+ return;
+ }
+ }
+ if (self->service_joined)
+ {
+ /* Only hardware-stop boundaries cancel the request-independent IN. The
+ * physical reader, partial reassembly and coalesced notifications survive
+ * ordinary owner handoffs. */
+ self->service_draining = TRUE;
+ goodix_transport_quiesce (dev, goodix_session_hardware_joined, NULL);
+ return;
+ }
+ if (self->session_open && !self->needs_reinit &&
+ !self->suspend_pending && !self->session_suspended)
+ goodix_scan_start_service (dev);
+}
+
+void
+goodix_session_service_done (FpDevice *dev, GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ self->service_active = FALSE;
+ if (error &&
+ !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED) &&
+ !g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_CANCELLED))
+ {
+ /* Maintenance stays off until the next action reconstructs the
+ * hardware session; nothing else retries in the background. */
+ self->needs_reinit = TRUE;
+ fp_warn ("Hardware maintenance stopped: %s", error->message);
+ }
+ g_clear_error (&error);
+ goodix_session_settle (dev);
+}
+
+void
+goodix_session_detach_action (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ g_assert (!self->service_active);
+ self->service_active = TRUE;
+}
+
+void
+goodix_session_start_action (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ /* Actions never queue behind power or close work; the core only blocks
+ * them itself once suspend has completed. */
+ if (self->suspend_pending || self->session_suspended)
+ {
+ fpi_device_action_error (dev, fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_BUSY, "Hardware session is suspended"));
+ return;
+ }
+ if (self->service_joined)
+ {
+ fpi_device_action_error (dev, g_error_new_literal (
+ G_IO_ERROR, G_IO_ERROR_CANCELLED,
+ "Hardware session is closing"));
+ return;
+ }
+ self->action_pending = TRUE;
+ if (self->service_active)
+ goodix_scan_join_service (dev);
+ else
+ goodix_session_settle (dev);
+}
+
+gboolean
+goodix_session_cancel_pending_action (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (!self->action_pending)
+ return FALSE;
+
+ /* Nothing was admitted yet. Detach only the request: the maintenance owner
+ * keeps its selected command and settles servicing through its own join. */
+ self->action_pending = FALSE;
+ fpi_device_action_error (dev, g_error_new_literal (
+ G_IO_ERROR, G_IO_ERROR_CANCELLED,
+ "Action cancelled during hardware handoff"));
+ return TRUE;
+}
+
+void
+goodix_session_action_done (FpDevice *dev, GError *error,
+ void (*complete) (FpDevice *, GError *))
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_CANCELLED))
+ {
+ g_clear_error (&error);
+ error = g_error_new_literal (G_IO_ERROR, G_IO_ERROR_CANCELLED,
+ "Action cancelled");
+ }
+ self->foreground_active = FALSE;
+ /* The application callback may start the next action reentrantly; the
+ * ownership state above is already consistent for that. */
+ complete (dev, error);
+ goodix_session_settle (dev);
+}
+
+void
+goodix_session_quiesce (FpDevice *dev,
+ void (*joined) (FpDevice *, gpointer), gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ g_assert (!self->service_joined);
+ self->service_joined = joined;
+ self->service_joined_data = data;
+ if (self->session_cancel)
+ g_cancellable_cancel (self->session_cancel);
+ if (self->service_active)
+ goodix_scan_join_service (dev);
+ else if (self->foreground_active)
+ {
+ GCancellable *io_cancel = fpi_device_get_cancellable (dev);
+
+ /* An OUT submitted before suspend still owns the foreground token.
+ * Revoke it as well as the CPU/scan token before awaiting the join. */
+ if (io_cancel)
+ g_cancellable_cancel (io_cancel);
+ if (self->cancel)
+ g_cancellable_cancel (self->cancel);
+ goodix_scan_stop_coordinator (dev, NULL);
+ }
+ else
+ goodix_session_settle (dev);
+}
+
+/* Open SSM — full device initialization */
+typedef enum {
+ GOODIX_OPEN_USB_RESET = 0,
+ GOODIX_OPEN_CLAIM_INTERFACE,
+ GOODIX_OPEN_BRING_UP,
+ GOODIX_OPEN_UPLOAD_CONFIG,
+ GOODIX_OPEN_VALIDATE_CONFIG,
+ GOODIX_OPEN_CAPTURE_REF,
+ GOODIX_OPEN_CAPTURE_REF_DONE,
+ GOODIX_OPEN_FINAL_FIRMWARE,
+ GOODIX_OPEN_FINAL_SLEEP,
+ GOODIX_OPEN_SLEEP,
+ GOODIX_OPEN_EC_POWER_OFF,
+ GOODIX_OPEN_EC_POWER_OFF_DONE,
+ GOODIX_OPEN_NUM_STATES,
+} GoodixOpenState;
+
+
+#ifdef GOODIX53X5_DEBUG
+static const gchar *
+goodix_open_state_name (GoodixOpenState state)
+{
+ switch (state)
+ {
+ case GOODIX_OPEN_USB_RESET:
+ return "usb_reset";
+ case GOODIX_OPEN_CLAIM_INTERFACE:
+ return "claim_interface";
+ case GOODIX_OPEN_BRING_UP:
+ return "bring_up";
+ case GOODIX_OPEN_UPLOAD_CONFIG:
+ return "upload_config";
+ case GOODIX_OPEN_VALIDATE_CONFIG:
+ return "validate_config";
+ case GOODIX_OPEN_CAPTURE_REF:
+ return "capture_ref";
+ case GOODIX_OPEN_CAPTURE_REF_DONE:
+ return "capture_ref_done";
+ case GOODIX_OPEN_FINAL_FIRMWARE:
+ return "final_firmware";
+ case GOODIX_OPEN_FINAL_SLEEP:
+ return "final_sleep";
+ case GOODIX_OPEN_SLEEP:
+ return "sleep";
+ case GOODIX_OPEN_EC_POWER_OFF:
+ return "ec_power_off";
+ case GOODIX_OPEN_EC_POWER_OFF_DONE:
+ return "ec_power_off_done";
+ case GOODIX_OPEN_NUM_STATES:
+ default:
+ return "unknown";
+ }
+}
+#endif
+
+gboolean
+goodix_load_psk (FpiDeviceGoodix53x5 *self,
+ GError **error)
+{
+ const gchar *path = GOODIX_PSK_STATE_FILE;
+ gchar *contents = NULL;
+ gsize length = 0;
+ gsize hex_length;
+ g_autoptr(GError) local_error = NULL;
+ gboolean success = FALSE;
+
+ memset (self->psk, 0, sizeof (self->psk));
+ self->psk_imported = FALSE;
+
+ if (!g_file_get_contents (path, &contents, &length, &local_error))
+ {
+ if (g_error_matches (local_error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
+ return TRUE;
+
+ g_propagate_prefixed_error (error, g_steal_pointer (&local_error),
+ "Failed to read PSK file %s: ", path);
+ return FALSE;
+ }
+
+ hex_length = length;
+ while (hex_length > 0 && g_ascii_isspace (contents[hex_length - 1]))
+ hex_length--;
+ if (hex_length != GOODIX_PSK_LEN * 2)
+ {
+ g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA,
+ "PSK file %s must contain exactly 64 hexadecimal characters",
+ path);
+ goto out;
+ }
+
+ for (gsize i = 0; i < GOODIX_PSK_LEN; i++)
+ {
+ gint high = g_ascii_xdigit_value (contents[i * 2]);
+ gint low = g_ascii_xdigit_value (contents[i * 2 + 1]);
+
+ if (high < 0 || low < 0)
+ {
+ g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA,
+ "PSK file %s contains non-hexadecimal data", path);
+ goto out;
+ }
+ self->psk[i] = (high << 4) | low;
+ }
+
+ self->psk_imported = TRUE;
+ fp_info ("Using imported GTLS PSK from %s", path);
+ success = TRUE;
+
+out:
+ OPENSSL_cleanse (contents, length);
+ g_free (contents);
+ if (!success)
+ OPENSSL_cleanse (self->psk, sizeof (self->psk));
+ return success;
+}
+
+/* ========================================================================
+ * Open SSM — full device initialization
+ * ======================================================================== */
+
+typedef enum {
+ GOODIX_PROBE_PING,
+ GOODIX_PROBE_FIRMWARE,
+ GOODIX_PROBE_AFTER_DELAY,
+ GOODIX_PROBE_NUM_STATES,
+} GoodixProbeState;
+
+typedef struct
+{
+ guint failures;
+ /* Firmware reads before @check decides without a version. */
+ guint reads;
+ GoodixFirmwareCheck check;
+} GoodixProbeData;
+
+static gboolean
+goodix_probe_cancelled (FpiSsm *ssm, FpDevice *dev)
+{
+ GCancellable *cancel = goodix_session_io_cancellable (dev);
+ gboolean removed = FALSE;
+
+ g_object_get (dev, "removed", &removed, NULL);
+ if (cancel && g_cancellable_is_cancelled (cancel))
+ {
+ fpi_ssm_mark_failed (ssm, g_error_new_literal (G_IO_ERROR, G_IO_ERROR_CANCELLED,
+ "Startup probe cancelled"));
+ return TRUE;
+ }
+ if (removed)
+ {
+ fpi_ssm_mark_failed (ssm, g_error_new_literal (G_USB_DEVICE_ERROR,
+ G_USB_DEVICE_ERROR_NO_DEVICE,
+ "Startup device removed"));
+ return TRUE;
+ }
+ return FALSE;
+}
+
+static void
+goodix_probe_result (FpiSsm *ssm, FpDevice *dev, guint8 status,
+ gboolean native_zero, GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixProbeData *data = fpi_ssm_get_data (ssm);
+
+ if (goodix_probe_cancelled (ssm, dev))
+ {
+ g_clear_error (&error);
+ return;
+ }
+ if (error && !native_zero)
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+ if (fpi_ssm_get_cur_state (ssm) == GOODIX_PROBE_PING)
+ {
+ g_clear_error (&error);
+ fpi_ssm_next_state (ssm);
+ }
+ else if (!error)
+ {
+ /* Native getter copies 64 cache bytes. Keep that cache untouched and
+ * give the Linux string consumer its own guaranteed terminator. */
+ g_free (self->fw_version);
+ self->fw_version = g_strndup ((const gchar *) self->shared_response,
+ sizeof (self->shared_response));
+ error = data->check (self->fw_version);
+ if (error)
+ fpi_ssm_mark_failed (ssm, error);
+ else
+ fpi_ssm_mark_completed (ssm);
+ }
+ else
+ {
+ g_clear_error (&error);
+ data->failures++;
+ /* Native sleeps after every failed query, including iteration five. */
+ fpi_ssm_jump_to_state_delayed (ssm, GOODIX_PROBE_AFTER_DELAY, 100);
+ }
+}
+
+static void
+goodix_probe_ssm_handler (FpiSsm *ssm, FpDevice *dev)
+{
+ GoodixProbeData *data = fpi_ssm_get_data (ssm);
+
+ if (goodix_probe_cancelled (ssm, dev))
+ return;
+ switch (fpi_ssm_get_cur_state (ssm))
+ {
+ case GOODIX_PROBE_PING:
+ case GOODIX_PROBE_FIRMWARE:
+ goodix_cmd_probe (ssm, dev, fpi_ssm_get_cur_state (ssm) == GOODIX_PROBE_FIRMWARE,
+ goodix_probe_result);
+ break;
+ case GOODIX_PROBE_AFTER_DELAY:
+ if (data->failures == data->reads)
+ {
+ GError *error = data->check (NULL);
+
+ if (error)
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ }
+ else
+ {
+ fp_dbg ("Startup firmware query exhausted; continuing device initialization");
+ fpi_ssm_mark_completed (ssm);
+ }
+ }
+ else
+ fpi_ssm_jump_to_state (ssm, GOODIX_PROBE_PING);
+ break;
+ }
+}
+
+void
+goodix_open_probe (FpiSsm *ssm, FpDevice *dev, guint reads, GoodixFirmwareCheck check)
+{
+ FpiSsm *probe = fpi_ssm_new (dev, goodix_probe_ssm_handler, GOODIX_PROBE_NUM_STATES);
+ GoodixProbeData *data = g_new0 (GoodixProbeData, 1);
+
+ data->reads = reads;
+ data->check = check;
+ fpi_ssm_set_data (probe, data, g_free);
+ fpi_ssm_start_subsm (ssm, probe);
+}
+
+typedef enum {
+ GOODIX_CHIP_INITIAL_RESET,
+ GOODIX_CHIP_READ,
+ GOODIX_CHIP_RECOVERY_RESET,
+ GOODIX_CHIP_AFTER_DELAY,
+ GOODIX_CHIP_NUM_STATES,
+} GoodixChipState;
+
+typedef struct
+{
+ guint failures;
+ gboolean initial_reset_requests_irq;
+} GoodixChipData;
+
+static void
+goodix_chip_result (FpiSsm *ssm, FpDevice *dev, guint8 status,
+ gboolean native_zero, GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixChipData *data = fpi_ssm_get_data (ssm);
+
+ if (goodix_probe_cancelled (ssm, dev))
+ {
+ g_clear_error (&error);
+ return;
+ }
+ if (error && !native_zero)
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+
+ if (fpi_ssm_get_cur_state (ssm) == GOODIX_CHIP_READ)
+ {
+ if (!error)
+ {
+ const guint8 *payload;
+ gsize length;
+
+ if (!goodix_cmd_parse_chip_id_reply (dev, &payload, &length, &error))
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+ if (length != 4)
+ {
+ fpi_ssm_mark_failed (ssm, fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_PROTO,
+ "Unexpected chip ID reply length: %zu", length));
+ return;
+ }
+
+ self->chip_id = goodix_crypto_decode_u32 (payload);
+ fp_dbg ("Chip ID: 0x%08x", self->chip_id);
+ /* usbinterface!180017ef8 recognizes these four families. A valid
+ * other family is unsupported by Linux, not failed identification. */
+ switch (self->chip_id >> 8)
+ {
+ case 0x2202:
+ case 0x2207:
+ case 0x2208:
+ case 0x220c:
+ if (!goodix_milan_runtime_subtype_for_chip (
+ self->chip_id, &self->milan_sensor_subtype))
+ fpi_ssm_mark_failed (ssm, fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_NOT_SUPPORTED,
+ "Native Milan runtime is unsupported for product 0x%04x chip 0x%08x",
+ g_usb_device_get_pid (fpi_device_get_usb_device (dev)),
+ self->chip_id));
+ else
+ fpi_ssm_mark_completed (ssm);
+ return;
+
+ default:
+ break;
+ }
+ }
+ g_clear_error (&error);
+ data->failures++;
+ fpi_ssm_next_state (ssm);
+ return;
+ }
+
+ /* device_enable ignores the first ordinary reset failure. The chip getter
+ * also ignores recovery reset failure and its IRQ value. Both delays occur
+ * after completion; the last failed read still resets and sleeps. */
+ g_clear_error (&error);
+ fpi_ssm_next_state_delayed (ssm,
+ fpi_ssm_get_cur_state (ssm) == GOODIX_CHIP_INITIAL_RESET ? 10 : 100);
+}
+
+static void
+goodix_chip_ssm_handler (FpiSsm *ssm, FpDevice *dev)
+{
+ GoodixChipData *data = fpi_ssm_get_data (ssm);
+
+ if (goodix_probe_cancelled (ssm, dev))
+ return;
+ switch (fpi_ssm_get_cur_state (ssm))
+ {
+ case GOODIX_CHIP_INITIAL_RESET:
+ case GOODIX_CHIP_RECOVERY_RESET:
+ goodix_cmd_reset_sensor (ssm, dev,
+ fpi_ssm_get_cur_state (ssm) == GOODIX_CHIP_RECOVERY_RESET ||
+ data->initial_reset_requests_irq,
+ goodix_chip_result);
+ break;
+
+ case GOODIX_CHIP_READ:
+ goodix_cmd_read_chip_id (ssm, dev, goodix_chip_result);
+ break;
+
+ case GOODIX_CHIP_AFTER_DELAY:
+ if (data->failures == 6)
+ fpi_ssm_mark_failed (ssm, fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_PROTO,
+ "Chip identification failed after six read cycles"));
+ else
+ fpi_ssm_jump_to_state (ssm, GOODIX_CHIP_READ);
+ break;
+ }
+}
+
+void
+goodix_open_identify_chip (FpiSsm *ssm, FpDevice *dev, gboolean initial_reset_requests_irq)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ /* Cold HAL construction deactivates the anchor before any reference
+ * outcome. Ordinary actions and in-place repairs do not reset it. */
+ self->profile9_fdt.drift_anchor_empty = TRUE;
+ goodix_health_reset (&self->health);
+ self->capture_callback_pending = FALSE;
+ FpiSsm *chip = fpi_ssm_new (dev, goodix_chip_ssm_handler, GOODIX_CHIP_NUM_STATES);
+ GoodixChipData *data = g_new0 (GoodixChipData, 1);
+
+ data->initial_reset_requests_irq = initial_reset_requests_irq;
+ fpi_ssm_set_data (chip, data, g_free);
+ fpi_ssm_start_subsm (ssm, chip);
+}
+
+typedef struct {
+ guint attempt;
+ GoodixChannelReason reason;
+ /* Attempts before giving up. */
+ guint limit;
+ GError *error;
+ GoodixGtlsRestartDone restart_done;
+ gpointer restart_data;
+} GoodixGtlsRetry;
+
+static void
+goodix_gtls_retry_free (GoodixGtlsRetry *retry)
+{
+ g_clear_error (&retry->error);
+ g_free (retry);
+}
+
+static void goodix_gtls_retry_handler (FpiSsm *ssm, FpDevice *dev);
+
+/* Returns a new SSM that runs up to @limit handshake attempts. */
+static FpiSsm *
+goodix_gtls_retry_new (FpDevice *dev, guint limit)
+{
+ GoodixGtlsRetry *retry = g_new0 (GoodixGtlsRetry, 1);
+ FpiSsm *ssm = fpi_ssm_new (dev, goodix_gtls_retry_handler, 2);
+
+ retry->limit = limit;
+ fpi_ssm_set_data (ssm, retry, (GDestroyNotify) goodix_gtls_retry_free);
+ return ssm;
+}
+
+/* Returns a new SSM for the handshake attempts open and resume make. */
+static FpiSsm *
+goodix_gtls_open_retry_new (FpDevice *dev)
+{
+ return goodix_gtls_retry_new (
+ dev, goodix_family (FPI_DEVICE_GOODIX53X5 (dev))->channel.attempts.open);
+}
+
+static void
+goodix_gtls_attempt_done (FpiSsm *attempt, FpDevice *dev, GError *error)
+{
+ FpiSsm *ssm = fpi_ssm_get_data (attempt);
+ GoodixGtlsRetry *retry = fpi_ssm_get_data (ssm);
+
+ if (!error)
+ {
+ fpi_ssm_mark_completed (ssm);
+ return;
+ }
+ /* Host cancellation, removal and ownership rejection are terminal. Ordinary
+ * native send/read/protocol failure retries the selected-PSK handshake only. */
+ if (!(g_error_matches (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO) ||
+ g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_IO) ||
+ g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_FAILED) ||
+ g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_NOT_SUPPORTED) ||
+ g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_INTERNAL) ||
+ g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_TIMED_OUT)))
+ {
+ if (!retry->restart_done)
+ FPI_DEVICE_GOODIX53X5 (dev)->open_gtls_failed = TRUE;
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+ retry->error = error;
+ guint delay = goodix_family (FPI_DEVICE_GOODIX53X5 (dev))->channel.retry_delay_ms;
+
+ if (delay)
+ fpi_ssm_jump_to_state_delayed (ssm, retry->attempt < retry->limit ? 0 : 1, delay);
+ else
+ fpi_ssm_jump_to_state (ssm, retry->attempt < retry->limit ? 0 : 1);
+}
+
+static void
+goodix_gtls_retry_handler (FpiSsm *ssm, FpDevice *dev)
+{
+ GoodixGtlsRetry *retry = fpi_ssm_get_data (ssm);
+ g_autoptr(GError) error = NULL;
+
+ if (g_cancellable_set_error_if_cancelled (goodix_session_io_cancellable (dev), &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ if (fpi_ssm_get_cur_state (ssm) == 1)
+ {
+ if (retry->restart_done)
+ {
+ /* Ordinary restart exhaustion never retires the hardware worker,
+ * whether or not an application currently owns a capture request. */
+ fp_dbg ("GTLS restart failed: %s", retry->error->message);
+ fpi_ssm_mark_completed (ssm);
+ return;
+ }
+ FPI_DEVICE_GOODIX53X5 (dev)->open_gtls_failed = TRUE;
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&retry->error));
+ return;
+ }
+ g_clear_error (&retry->error);
+ retry->attempt++;
+ FpiSsm *attempt = goodix_family (FPI_DEVICE_GOODIX53X5 (dev))->channel.attempt_new (dev, retry->reason);
+
+ fpi_ssm_set_data (attempt, ssm, NULL);
+ fpi_ssm_start (attempt, goodix_gtls_attempt_done);
+}
+
+static void
+goodix_gtls_restart_done (FpiSsm *ssm, FpDevice *dev, GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixGtlsRetry *retry = fpi_ssm_get_data (ssm);
+
+ self->gtls_restart_active = FALSE;
+ /* Host cancellation/removal can interrupt key replacement. The next action
+ * must not treat that incomplete session as an established one. */
+ if (error)
+ self->needs_reinit = TRUE;
+ retry->restart_done (dev, error, retry->restart_data);
+}
+
+void
+goodix_start_gtls_restart (FpDevice *dev, GoodixGtlsRestartDone done,
+ gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ const GoodixChannelAttempts *attempts = &goodix_family (self)->channel.attempts;
+ gboolean reconnect = self->reconnect_pending != 0;
+ FpiSsm *ssm = goodix_gtls_retry_new (dev, reconnect ?
+ attempts->reconnect : attempts->after_failed_read);
+ GoodixGtlsRetry *retry = fpi_ssm_get_data (ssm);
+
+ g_assert (!self->transport && !self->gtls_restart_active);
+ retry->reason = reconnect ? GOODIX_CHANNEL_RECONNECT : GOODIX_CHANNEL_FAILED_READ;
+ self->reconnect_requested = reconnect;
+ if (reconnect)
+ self->reconnect_pending--;
+ self->gtls_restart_pending = self->reconnect_pending != 0;
+ self->gtls_restart_active = TRUE;
+ retry->restart_done = done;
+ retry->restart_data = data;
+ fpi_ssm_start (ssm, goodix_gtls_restart_done);
+}
+
+/* deviceInit ignores ordinary allbase, final-version and mode-2 results.
+ * Configuration failure still exits allbase before its first manual/image;
+ * only the cold owner continues to its common initialization tail. */
+static void
+goodix_open_native_result (FpiSsm *ssm, FpDevice *dev, guint8 status,
+ gboolean native_zero, GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ gboolean failed = error != NULL;
+
+ if (error && !native_zero)
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+ g_clear_error (&error);
+ if (goodix_probe_cancelled (ssm, dev))
+ return;
+
+ switch (fpi_ssm_get_cur_state (ssm))
+ {
+ case GOODIX_OPEN_UPLOAD_CONFIG:
+ if (failed)
+ {
+ self->profile9_fdt.base_valid = FALSE;
+ self->profile9_fdt.initial_recovery_pending = TRUE;
+ fpi_ssm_jump_to_state (ssm, GOODIX_OPEN_FINAL_FIRMWARE);
+ }
+ else
+ {
+ fpi_ssm_next_state (ssm);
+ }
+ break;
+
+ case GOODIX_OPEN_FINAL_FIRMWARE:
+ if (!failed)
+ {
+ g_free (self->fw_version);
+ self->fw_version = g_strndup ((const gchar *) self->shared_response,
+ sizeof (self->shared_response));
+ }
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_OPEN_FINAL_SLEEP:
+ /* Completed native mode request, including ordinary exhaustion. The
+ * command owner has published requested mode 2; no EC-off belongs here. */
+ fpi_ssm_jump_to_state (ssm, GOODIX_OPEN_NUM_STATES);
+ break;
+
+ default:
+ g_assert_not_reached ();
+ }
+}
+
+/* Checks whether @hash, as the sensor reports it, is the SHA-256 of the PSK
+ * this driver holds. */
+static gboolean
+goodix_psk_hash_is_current (FpiDeviceGoodix53x5 *self, const guint8 *hash, gsize len)
+{
+ g_autoptr(GChecksum) sha = g_checksum_new (G_CHECKSUM_SHA256);
+ guint8 expected[32];
+ gsize expected_len = sizeof (expected);
+
+ g_checksum_update (sha, self->psk, GOODIX_PSK_LEN);
+ g_checksum_get_digest (sha, expected, &expected_len);
+ return len >= sizeof (expected) && memcmp (hash, expected, sizeof (expected)) == 0;
+}
+
+static GError *
+goodix_psk_mismatch_error (void)
+{
+ return fpi_device_error_new_msg (FP_DEVICE_ERROR_DATA_INVALID,
+ "Sensor PSK does not match: the reader holds a key "
+ "Windows Hello set, and this driver never changes it");
+}
+
+gboolean
+goodix_psk_hash_reply_matches (FpDevice *dev, guint32 slot, gboolean *matches, GError **error)
+{
+ const guint8 *hash;
+ gsize hash_len;
+
+ if (!goodix_cmd_parse_production_read_reply (dev, slot, &hash, &hash_len))
+ {
+ g_set_error_literal (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "Failed to read PSK hash");
+ return FALSE;
+ }
+ *matches = goodix_psk_hash_is_current (FPI_DEVICE_GOODIX53X5 (dev), hash, hash_len);
+ fp_info ("Sensor PSK hash %s the %s key", *matches ? "matches" : "does not match",
+ FPI_DEVICE_GOODIX53X5 (dev)->psk_imported ? "imported" : "all-zero factory");
+ return TRUE;
+}
+
+gboolean
+goodix_require_current_psk (FpDevice *dev, guint32 slot, GError **error)
+{
+ gboolean matches;
+
+ if (!goodix_psk_hash_reply_matches (dev, slot, &matches, error))
+ return FALSE;
+ if (!matches)
+ g_propagate_error (error, goodix_psk_mismatch_error ());
+ return matches;
+}
+
+gboolean
+goodix_open_parse_otp (FpDevice *dev, GError **error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ const guint8 *pl;
+ gsize pl_len;
+
+ if (!goodix_cmd_parse_otp_reply (dev, &pl, &pl_len, NULL))
+ {
+ g_propagate_error (error, fpi_device_error_new_msg (FP_DEVICE_ERROR_PROTO,
+ "Failed to parse OTP response"));
+ return FALSE;
+ }
+
+ g_clear_pointer (&self->otp_data, g_free);
+ self->otp_data = g_memdup2 (pl, pl_len);
+ self->otp_len = pl_len;
+
+ if (!goodix_device_verify_otp (pl, pl_len))
+ {
+ g_propagate_error (error, fpi_device_error_new_msg (FP_DEVICE_ERROR_PROTO,
+ "OTP hash verification failed"));
+ return FALSE;
+ }
+
+ goodix_milan_persistence_prepare (dev);
+ goodix_device_parse_otp (pl, pl_len, &self->calib);
+ /* Sensor checking reseeds current/default; native static adjustment
+ * history is owned by live capture, not HAL reconstruction. */
+ self->dynamic_dac.default_dac = self->calib.dac_h;
+ return TRUE;
+}
+
+void
+goodix_open_channel (FpiSsm *ssm, FpDevice *dev)
+{
+ FPI_DEVICE_GOODIX53X5 (dev)->open_gtls_failed = FALSE;
+ fpi_ssm_start_subsm (ssm, goodix_gtls_open_retry_new (dev));
+}
+
+static void
+goodix_open_ssm_handler (FpiSsm *ssm,
+ FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixOpenState state = fpi_ssm_get_cur_state (ssm);
+
+ goodix_debug_timing_open_state (self, dev, goodix_open_state_name (state),
+ g_get_monotonic_time ());
+
+ switch (state)
+ {
+ case GOODIX_OPEN_USB_RESET:
+ {
+ GError *error = NULL;
+
+ if (!self->open_usb_reset_required)
+ {
+ fpi_ssm_next_state (ssm);
+ return;
+ }
+
+ if (!g_usb_device_reset (fpi_device_get_usb_device (dev), &error))
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+
+ self->open_usb_reset_required = FALSE;
+ }
+
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_OPEN_CLAIM_INTERFACE:
+ {
+ GError *error = NULL;
+
+ if (!g_usb_device_claim_interface (
+ fpi_device_get_usb_device (dev), GOODIX_USB_INTERFACE (dev),
+ G_USB_DEVICE_CLAIM_INTERFACE_BIND_KERNEL_DRIVER, &error))
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+
+ self->usb_interface_claimed = TRUE;
+ fpi_ssm_next_state (ssm);
+ }
+ break;
+
+ case GOODIX_OPEN_BRING_UP:
+ fpi_ssm_start_subsm (ssm, goodix_family (self)->open_new (dev));
+ break;
+
+ case GOODIX_OPEN_UPLOAD_CONFIG:
+ {
+ self->open_ref_powered = FALSE;
+
+ fp_info ("%s handshake completed", goodix_family (self)->channel.name);
+ goodix_cmd_restore_config (ssm, dev, goodix_open_native_result);
+ }
+ break;
+
+ case GOODIX_OPEN_VALIDATE_CONFIG:
+ {
+ if (!goodix_cmd_parse_config_reply (dev))
+ {
+ fpi_ssm_mark_failed (ssm,
+ fpi_device_error_new_msg (FP_DEVICE_ERROR_PROTO,
+ "Config upload failed"));
+ return;
+ }
+
+ fpi_ssm_next_state (ssm);
+ }
+ break;
+
+ case GOODIX_OPEN_CAPTURE_REF:
+ goodix_milan_base_start_ensure_subsm (ssm, dev, FALSE);
+ break;
+
+ case GOODIX_OPEN_CAPTURE_REF_DONE:
+ /* Ordinary allbase failure leaves recovery pending, not a valid image.
+ * The cold owner still performs its final query and mode-2 publication. */
+ self->open_ref_powered = self->milan_generation != NULL;
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_OPEN_FINAL_FIRMWARE:
+ if (!goodix_probe_cancelled (ssm, dev))
+ goodix_cmd_probe (ssm, dev, TRUE, goodix_open_native_result);
+ break;
+
+ case GOODIX_OPEN_FINAL_SLEEP:
+ if (!goodix_probe_cancelled (ssm, dev))
+ goodix_cmd_set_sleep_mode_result (ssm, dev, goodix_open_native_result);
+ break;
+
+ case GOODIX_OPEN_SLEEP:
+ /* Defensive host-error cleanup is separate from the native cold tail. */
+ if (self->open_ref_powered)
+ goodix_cmd_set_sleep_mode (ssm, dev);
+ else
+ fpi_ssm_jump_to_state (ssm, GOODIX_OPEN_NUM_STATES);
+ break;
+
+ case GOODIX_OPEN_EC_POWER_OFF:
+ /* Native successful initialization ends after sleep. Retain the old
+ * defensive EC shutdown only when that cleanup has failed. */
+ if (fpi_ssm_get_error (ssm))
+ goodix_cmd_ec_control (ssm, dev, FALSE);
+ else
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_OPEN_EC_POWER_OFF_DONE:
+ self->open_ref_powered = FALSE;
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_OPEN_NUM_STATES:
+ g_assert_not_reached ();
+ break;
+ }
+}
+
+/* Forgets the channel's session and keys, where it keeps any. */
+static void
+goodix_channel_discard (FpiDeviceGoodix53x5 *self)
+{
+ const GoodixChannel *channel = &goodix_family (self)->channel;
+
+ if (channel->discard)
+ channel->discard (self);
+}
+
+static void
+goodix_cleanup_failed_open (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GUsbDevice *usb_dev = fpi_device_get_usb_device (dev);
+ g_autoptr(GError) cleanup_error = NULL;
+
+ /* Transport is joined and this open will not retry. A failed open
+ * will not receive the ordinary close callback. */
+ g_clear_object (&self->cancel);
+ g_clear_pointer (&self->otp_data, g_free);
+ self->otp_len = 0;
+ g_clear_pointer (&self->fw_version, g_free);
+ g_clear_pointer (&self->rx.buf, g_free);
+ self->reply_payload = NULL;
+ self->reply_payload_len = 0;
+
+ if (self->usb_interface_claimed)
+ {
+ if (!g_usb_device_release_interface (usb_dev, GOODIX_USB_INTERFACE (dev), 0,
+ &cleanup_error))
+ fp_warn ("Failed to release USB interface after open failure: %s",
+ cleanup_error->message);
+
+ self->usb_interface_claimed = FALSE;
+ g_clear_error (&cleanup_error);
+ }
+
+ if (!g_usb_device_close (usb_dev, &cleanup_error))
+ fp_warn ("Failed to close USB device after open failure: %s",
+ cleanup_error->message);
+}
+
+static void
+goodix_open_complete_after_idle (FpDevice *dev, gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GError *error = data;
+
+ if (error)
+ {
+ /* Reset/close ends the transport that could complete retained data.
+ * A completion winning idle cancellation may have just appended it. */
+ goodix_transport_invalidate (dev);
+ self->open_ref_powered = FALSE;
+ goodix_milan_generation_retain_process (dev);
+ g_clear_pointer (&self->hardware_reference, g_free);
+ self->hardware_refresh_pending = FALSE;
+ goodix_milan_persistence_clear (dev);
+ OPENSSL_cleanse (self->psk, sizeof (self->psk));
+ goodix_channel_discard (self);
+ self->psk_imported = FALSE;
+ goodix_debug_timing_open_done (self, dev, error->message);
+ fpi_device_report_finger_status (dev, FP_FINGER_STATUS_NONE);
+
+ if (!self->open_recovery_attempted && !self->open_gtls_failed &&
+ !fpi_device_action_is_cancelled (dev) &&
+ !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED) &&
+ !g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_NO_DEVICE) &&
+ error->domain != FP_DEVICE_RETRY)
+ {
+ self->open_recovery_attempted = TRUE;
+ if (self->usb_interface_claimed)
+ {
+ g_usb_device_release_interface (fpi_device_get_usb_device (dev),
+ GOODIX_USB_INTERFACE (dev), 0, NULL);
+ self->usb_interface_claimed = FALSE;
+ }
+ self->open_usb_reset_required = TRUE;
+ g_clear_error (&error);
+ goodix_start_open_ssm (dev);
+ return;
+ }
+
+ fp_warn ("Device open failed: %s", error->message);
+ goodix_cleanup_failed_open (dev);
+ fpi_device_open_complete (dev, error);
+ return;
+ }
+
+ fp_info ("Device initialization complete");
+ self->open_ref_powered = FALSE;
+ self->open_usb_reset_required = FALSE;
+ goodix_debug_timing_open_done (self, dev, NULL);
+ self->needs_reinit = FALSE;
+ self->session_open = TRUE;
+ goodix_session_settle (dev);
+ fpi_device_open_complete (dev, NULL);
+}
+
+static void
+goodix_open_ssm_done (FpiSsm *ssm, FpDevice *dev, GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ self->task_ssm = NULL;
+ /* The SSM is freed on return. Transfer only its completion error to the
+ * join callback; the open action and idle owner retain the device. */
+ if (error)
+ goodix_transport_quiesce (dev, goodix_open_complete_after_idle, error);
+ else
+ goodix_open_complete_after_idle (dev, NULL);
+}
+
+void
+goodix_start_open_ssm (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ FpiSsm *ssm;
+
+ g_clear_object (&self->cancel);
+ self->cancel = g_cancellable_new ();
+ self->open_gtls_failed = FALSE;
+ ssm = fpi_ssm_new_full (dev, goodix_open_ssm_handler,
+ GOODIX_OPEN_NUM_STATES,
+ GOODIX_OPEN_SLEEP,
+ "goodix-open");
+ self->task_ssm = ssm;
+ fpi_ssm_start (ssm, goodix_open_ssm_done);
+}
+
+/* ========================================================================
+ * Cold hardware recovery
+ * ======================================================================== */
+
+static void
+goodix_reinit_idle_joined (FpDevice *dev, gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ FpiSsm *sub;
+
+ /* A USB reset ends the transport that could complete the retained packet. */
+ goodix_transport_invalidate (dev);
+
+ fp_info ("Reinitializing hardware session");
+ self->action_epoch++;
+ goodix_milan_generation_retain_process (dev);
+ g_clear_pointer (&self->hardware_reference, g_free);
+ self->hardware_refresh_pending = FALSE;
+ self->open_recovery_attempted = FALSE;
+ self->open_gtls_failed = FALSE;
+ self->open_usb_reset_required = TRUE;
+
+ if (self->usb_interface_claimed)
+ {
+ g_autoptr(GError) release_error = NULL;
+
+ /* This is expected to fail with EINVAL after an S4 reset because the
+ * kernel already dropped the claim; recovery proceeds either way. */
+ if (!g_usb_device_release_interface (fpi_device_get_usb_device (dev),
+ GOODIX_USB_INTERFACE (dev),
+ 0, &release_error))
+ fp_dbg ("Releasing stale USB interface before reinit failed "
+ "(expected after S4 reset): %s", release_error->message);
+
+ self->usb_interface_claimed = FALSE;
+ }
+
+ sub = fpi_ssm_new_full (dev, goodix_open_ssm_handler,
+ GOODIX_OPEN_NUM_STATES,
+ GOODIX_OPEN_SLEEP,
+ "goodix-reinit");
+ fpi_ssm_start_subsm (data, sub);
+}
+
+/**
+ * If the hardware session is invalid, join reception, release any stale
+ * interface claim and run full initialization as a sub-SSM of @ssm. This is
+ * also the once-only fallback from warm resume; successful re-keying after
+ * system sleep does not enter this USB reset/calibration/reference path.
+ * Returns TRUE if reinit was scheduled (caller returns and the parent advances
+ * when it completes), FALSE if no reinit was needed.
+ */
+gboolean
+goodix_maybe_start_reinit_subsm (FpiSsm *ssm, FpDevice *dev)
+{
+ if (!FPI_DEVICE_GOODIX53X5 (dev)->needs_reinit)
+ return FALSE;
+
+ /* Join before either interface release or USB reset, just as close does. */
+ goodix_transport_quiesce (dev, goodix_reinit_idle_joined, ssm);
+ return TRUE;
+}
+
+/**
+ * TRUE for errors that indicate the USB device/claim is likely stale or
+ * gone (e.g. system slept while the device was claimed but idle, so the
+ * driver suspend hook never ran). Setting needs_reinit on these makes the
+ * next action attempt self-heal with a full reinitialization.
+ */
+gboolean
+goodix_error_indicates_stale_device (const GError *error)
+{
+ return g_error_matches (error, G_USB_DEVICE_ERROR,
+ G_USB_DEVICE_ERROR_TIMED_OUT) ||
+ g_error_matches (error, G_USB_DEVICE_ERROR,
+ G_USB_DEVICE_ERROR_NO_DEVICE) ||
+ g_error_matches (error, G_USB_DEVICE_ERROR,
+ G_USB_DEVICE_ERROR_NOT_OPEN) ||
+ g_error_matches (error, G_USB_DEVICE_ERROR,
+ G_USB_DEVICE_ERROR_IO) ||
+ g_error_matches (error, G_USB_DEVICE_ERROR,
+ G_USB_DEVICE_ERROR_FAILED);
+}
+
+/* ========================================================================
+ * Close
+ * ======================================================================== */
+
+static void
+goodix_session_close_joined (FpDevice *dev, gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GError *error = NULL;
+
+ self->action_epoch++;
+ if (self->cancel)
+ g_cancellable_cancel (self->cancel);
+ g_clear_object (&self->milan_task);
+ g_clear_object (&self->cancel);
+ g_clear_object (&self->session_cancel);
+ self->session_suspended = FALSE;
+ self->session_open = FALSE;
+ goodix_clear_pending_result_report (self);
+ g_clear_pointer (&self->otp_data, g_free);
+ g_clear_pointer (&self->fw_version, g_free);
+ goodix_transport_invalidate (dev);
+ g_clear_pointer (&self->rx.buf, g_free);
+#ifdef GOODIX53X5_DEBUG
+ g_clear_pointer (&self->captured_image, g_free);
+#endif
+ g_clear_pointer (&self->captured_raw_image, g_free);
+ g_clear_pointer (&self->pending_persistence_state, g_free);
+ goodix_milan_generation_retain_process (dev);
+ g_clear_pointer (&self->hardware_reference, g_free);
+ self->hardware_refresh_pending = FALSE;
+ g_clear_pointer (&self->enroll_transaction,
+ goodix_milan_enrollment_transaction_free);
+ goodix_milan_persistence_clear (dev);
+ g_clear_error (&self->pending_enroll_error);
+ OPENSSL_cleanse (self->psk, sizeof (self->psk));
+ goodix_channel_discard (self);
+ self->psk_imported = FALSE;
+
+ g_usb_device_release_interface (fpi_device_get_usb_device (dev),
+ GOODIX_USB_INTERFACE (dev), 0, &error);
+ self->usb_interface_claimed = FALSE;
+
+ fpi_device_close_complete (dev, error);
+}
+
+void
+goodix_session_close (FpDevice *dev)
+{
+ /* The paired core rejects close while a power task is pending and admits
+ * it for a quiesced suspended session, which needs no hardware I/O here. */
+ goodix_session_quiesce (dev, goodix_session_close_joined, NULL);
+}
+
+/* ========================================================================
+ * Suspend / resume policy
+ *
+ * Suspend joins every hardware owner, sleeps the sensor and powers the EC
+ * off, retaining the host calibration/reference/FDT tuple. Resume reclaims
+ * USB and re-keys GTLS without resetting that tuple. Existing hardware faults
+ * or failed warm reconstruction take the cold path once before completion.
+ * ======================================================================== */
+
+static void
+goodix_suspend_joined (FpDevice *dev, gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixRequestedMode requested_mode = self->requested_mode;
+
+ /* Retire packets and notifications, not the retained HAL's mode or bases. */
+ goodix_transport_invalidate (dev);
+ self->requested_mode = requested_mode;
+ if (data)
+ self->needs_reinit = TRUE;
+ self->suspend_pending = FALSE;
+ self->session_suspended = TRUE;
+ fpi_device_suspend_complete (dev, data);
+}
+
+static void
+goodix_suspend_power_done (FpiSsm *ssm, FpDevice *dev, GError *error)
+{
+ FPI_DEVICE_GOODIX53X5 (dev)->task_ssm = NULL;
+ goodix_transport_quiesce (dev, goodix_suspend_joined, error);
+}
+
+static void
+goodix_suspend_power (FpiSsm *ssm, FpDevice *dev)
+{
+ if (fpi_ssm_get_cur_state (ssm) == 0)
+ goodix_cmd_set_sleep_mode (ssm, dev);
+ else
+ goodix_cmd_ec_control (ssm, dev, FALSE);
+}
+
+static void
+goodix_suspend_service_joined (FpDevice *dev, gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ FpiSsm *ssm;
+
+ g_clear_object (&self->session_cancel);
+ self->session_cancel = g_cancellable_new ();
+ ssm = fpi_ssm_new (dev, goodix_suspend_power, 2);
+ self->task_ssm = ssm;
+ fpi_ssm_start (ssm, goodix_suspend_power_done);
+}
+
+void
+goodix_session_suspend (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ self->suspend_pending = TRUE;
+ goodix_session_quiesce (dev, goodix_suspend_service_joined, NULL);
+}
+
+typedef enum {
+ GOODIX_RESUME_WARM,
+ GOODIX_RESUME_COLD,
+ GOODIX_RESUME_NUM_STATES,
+} GoodixResumeState;
+
+typedef struct
+{
+ gint64 started_us;
+ gboolean cold;
+} GoodixResumeData;
+
+static void
+goodix_resume_joined (FpDevice *dev, gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GError *error = data;
+
+ self->session_suspended = FALSE;
+ if (error)
+ {
+ /* Neither cancellation nor failed reconstruction grants readiness. */
+ self->needs_reinit = TRUE;
+ goodix_transport_invalidate (dev);
+ fp_warn ("Hardware reconstruction after resume failed: %s", error->message);
+ }
+ else
+ {
+ self->needs_reinit = FALSE;
+ }
+ goodix_session_settle (dev);
+ fpi_device_resume_complete (dev, error);
+}
+
+static void
+goodix_resume_done (FpiSsm *ssm, FpDevice *dev, GError *error)
+{
+#ifdef GOODIX53X5_DEBUG
+ GoodixResumeData *data = fpi_ssm_get_data (ssm);
+
+ g_message ("Hardware resume %s (%s): %.2f ms",
+ error ? "failed" : "ready", data->cold ? "cold" : "warm",
+ (g_get_monotonic_time () - data->started_us) / 1000.0);
+#endif
+ FPI_DEVICE_GOODIX53X5 (dev)->task_ssm = NULL;
+ if (error)
+ goodix_transport_quiesce (dev, goodix_resume_joined, error);
+ else
+ goodix_resume_joined (dev, NULL);
+}
+
+/* The physical reader is joined before either interface operation. Release
+ * also clears libusb's remembered claim after the kernel reset-resumes S4. */
+static void
+goodix_resume_warm (FpiSsm *ssm, FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (goodix_probe_cancelled (ssm, dev))
+ return;
+ if (fpi_ssm_get_cur_state (ssm) == 0)
+ {
+ g_autoptr(GError) error = NULL;
+
+ if (self->usb_interface_claimed)
+ {
+ /* A stale release can return EINVAL after reset-resume. The fresh
+ * claim with kernel-driver detach establishes actual ownership. */
+ if (!g_usb_device_release_interface (fpi_device_get_usb_device (dev),
+ GOODIX_USB_INTERFACE (dev), 0, &error))
+ fp_dbg ("Releasing USB interface before warm resume: %s", error->message);
+ self->usb_interface_claimed = FALSE;
+ g_clear_error (&error);
+ }
+ if (!g_usb_device_claim_interface (fpi_device_get_usb_device (dev),
+ GOODIX_USB_INTERFACE (dev),
+ G_USB_DEVICE_CLAIM_INTERFACE_BIND_KERNEL_DRIVER,
+ &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ self->usb_interface_claimed = TRUE;
+ fpi_ssm_next_state (ssm);
+ }
+ else
+ {
+ /* usbinterface!180020970 resume uses the same two three-attempt groups
+ * as cold initialization, not the single group of the event restart.
+ * Reuse only the handshake owner, with the already selected PSK. */
+ fpi_ssm_start_subsm (ssm, goodix_gtls_open_retry_new (dev));
+ }
+}
+
+static void
+goodix_resume_warm_done (FpiSsm *ssm, FpDevice *dev, GError *error)
+{
+ FpiSsm *parent = fpi_ssm_get_data (ssm);
+
+ if (!error)
+ {
+ fpi_ssm_mark_completed (parent);
+ }
+ else if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED) ||
+ g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_CANCELLED) ||
+ g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_NO_DEVICE))
+ {
+ fpi_ssm_mark_failed (parent, error);
+ }
+ else
+ {
+ fp_warn ("Warm resume failed; reconstructing hardware once: %s", error->message);
+ g_clear_error (&error);
+ FPI_DEVICE_GOODIX53X5 (dev)->needs_reinit = TRUE;
+ fpi_ssm_next_state (parent);
+ }
+}
+
+static void
+goodix_resume_handler (FpiSsm *ssm, FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixResumeData *data = fpi_ssm_get_data (ssm);
+
+ switch ((GoodixResumeState) fpi_ssm_get_cur_state (ssm))
+ {
+ case GOODIX_RESUME_WARM:
+ if (self->needs_reinit)
+ {
+ fpi_ssm_next_state (ssm);
+ }
+ else
+ {
+ FpiSsm *warm = fpi_ssm_new (dev, goodix_resume_warm, 2);
+
+ fpi_ssm_set_data (warm, ssm, NULL);
+ fpi_ssm_start (warm, goodix_resume_warm_done);
+ }
+ break;
+
+ case GOODIX_RESUME_COLD:
+ data->cold = TRUE;
+ if (!goodix_maybe_start_reinit_subsm (ssm, dev))
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_RESUME_NUM_STATES:
+ g_assert_not_reached ();
+ }
+}
+
+void
+goodix_session_resume (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixResumeData *data = g_new0 (GoodixResumeData, 1);
+ FpiSsm *ssm;
+
+ data->started_us = g_get_monotonic_time ();
+ g_clear_object (&self->cancel);
+ self->cancel = g_cancellable_new ();
+ g_clear_object (&self->session_cancel);
+ self->session_cancel = g_cancellable_new ();
+ ssm = fpi_ssm_new (dev, goodix_resume_handler, GOODIX_RESUME_NUM_STATES);
+ fpi_ssm_set_data (ssm, data, g_free);
+ self->task_ssm = ssm;
+ fpi_ssm_start (ssm, goodix_resume_done);
+}
diff --git a/libfprint/drivers/goodix53x5/device/session.h b/libfprint/drivers/goodix53x5/device/session.h
new file mode 100644
index 0000000..b12c3b1
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/session.h
@@ -0,0 +1,125 @@
+/*
+ * Goodix 53x5 driver for libfprint — Device session (open, GTLS, reinit)
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#pragma once
+
+#include "driver-private.h"
+
+/**
+ * Start the full open/initialization SSM as the top-level task SSM and
+ * complete the libfprint open action when it finishes.
+ */
+void goodix_start_open_ssm (FpDevice *dev);
+
+typedef void (*GoodixGtlsRestartDone) (FpDevice *dev,
+ GError *error,
+ gpointer data);
+
+/* How long a secure-channel handshake waits for each reply from the sensor. */
+#define GOODIX_CHANNEL_REPLY_TIMEOUT_MS 2000
+
+/* Run the native three-attempt restart with the retained selected PSK.
+ * The caller joins the asynchronous completion before resuming scan work. */
+void goodix_start_gtls_restart (FpDevice *dev,
+ GoodixGtlsRestartDone done,
+ gpointer data);
+
+/**
+ * If the hardware session is invalid, release any stale interface claim and
+ * run the full open-time initialization SSM as a sub-SSM of @ssm.
+ *
+ * Returns TRUE if a reinit sub-SSM was started (caller returns and the
+ * parent advances when it completes), FALSE if no reinit was needed.
+ */
+gboolean goodix_maybe_start_reinit_subsm (FpiSsm *ssm,
+ FpDevice *dev);
+
+/**
+ * TRUE for errors that indicate the USB device/claim is likely stale or
+ * gone. Setting needs_reinit on these makes the next action attempt
+ * self-heal with a full reinitialization.
+ */
+gboolean goodix_error_indicates_stale_device (const GError *error);
+
+/**
+ * Handle system sleep/wake while the device is open, including ACTION_NONE.
+ * Suspend cancels/joins the selected hardware owner and CPU consumer, sends
+ * sleep/EC-off, then joins reception while retaining calibration/reference/FDT
+ * state. Resume reclaims USB and re-keys GTLS, with one cold reconstruction on
+ * failure, then restarts packet-driven servicing before completing.
+ */
+void goodix_session_suspend (FpDevice *dev);
+void goodix_session_resume (FpDevice *dev);
+
+/* Join every hardware owner, release the interface and complete the close. */
+void goodix_session_close (FpDevice *dev);
+
+/* Background and power owners use session_cancel even during foreground
+ * admission. Only foreground/open callers use libfprint's action token. */
+GCancellable *goodix_session_io_cancellable (FpDevice *dev);
+
+/* Shared steps of a family's bring-up (GoodixFamily.open_new). */
+
+/* Returns NULL to accept @firmware, which is NULL when every read failed, or
+ * the error that fails open. */
+typedef GError *(*GoodixFirmwareCheck) (const char *firmware);
+
+/* Wakes the sensor and reads its firmware version, up to @reads times with
+ * the native 100 ms sleep after each failure, then asks @check. */
+void goodix_open_probe (FpiSsm *ssm, FpDevice *dev, guint reads,
+ GoodixFirmwareCheck check);
+/* Resets the sensor and reads its chip ID, up to six read cycles; the first
+ * reset asks for the IRQ status reply where @initial_reset_requests_irq. */
+void goodix_open_identify_chip (FpiSsm *ssm, FpDevice *dev,
+ gboolean initial_reset_requests_irq);
+/* Verifies and parses the OTP reply the previous state read. */
+gboolean goodix_open_parse_otp (FpDevice *dev, GError **error);
+/* Runs the open handshake attempts of the family's channel. */
+void goodix_open_channel (FpiSsm *ssm, FpDevice *dev);
+
+/* Selects the PSK for this open: the imported key in the state file, or the
+ * default all-zero PSK when there is none. */
+gboolean goodix_load_psk (FpiDeviceGoodix53x5 *self, GError **error);
+/* Sets @matches to whether the PSK hash the sensor returned in preset @slot
+ * is the hash of the PSK this driver holds. Fails when the reply does not parse. */
+gboolean goodix_psk_hash_reply_matches (FpDevice *dev, guint32 slot,
+ gboolean *matches, GError **error);
+/* Checks that the PSK hash the sensor returned in preset @slot is the hash of
+ * the PSK this driver holds. Fails when the reply does not parse or the hash
+ * differs, which a sensor the driver never provisions cannot recover from. */
+gboolean goodix_require_current_psk (FpDevice *dev, guint32 slot, GError **error);
+
+/* Every hardware owner reports here when it stops; the session then starts
+ * the pending action, the requested reader join, or idle maintenance. */
+void goodix_session_settle (FpDevice *dev);
+/* The idle service or a detached deactivation tail finished. A terminal error
+ * disables maintenance until the next action reconstructs the session. */
+void goodix_session_service_done (FpDevice *dev, GError *error);
+/* The coordinator hands a finished action back and keeps running its
+ * deactivation tail as background maintenance. */
+void goodix_session_detach_action (FpDevice *dev);
+void goodix_session_quiesce (FpDevice *dev,
+ void (*joined) (FpDevice *, gpointer),
+ gpointer data);
+void goodix_session_start_action (FpDevice *dev);
+/* Complete an unadmitted request without taking ownership of maintenance I/O. */
+gboolean goodix_session_cancel_pending_action (FpDevice *dev);
+/* Deliver the action's outcome, then settle the next hardware owner. */
+void goodix_session_action_done (FpDevice *dev, GError *error,
+ void (*complete) (FpDevice *, GError *));
diff --git a/libfprint/drivers/goodix53x5/device/transport.c b/libfprint/drivers/goodix53x5/device/transport.c
new file mode 100644
index 0000000..935c9e9
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/transport.c
@@ -0,0 +1,1546 @@
+/*
+ * Goodix 53x5 driver for libfprint — USB transport and command execution
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/transport.h"
+#include "device/commands.h"
+#include "device/calibration.h"
+#include "device/image.h"
+#include "device/session.h"
+
+#include <string.h>
+
+/* USB chunk size */
+#define GOODIX_USB_READ_SIZE 0x8000
+#define GOODIX_MCU_RX_SIZE (0x40000)
+
+#define GOODIX_FDT_EVENT_PAYLOAD_LEN (4 + GOODIX_FDT_BASE_LEN)
+#define GOODIX_PROTO_CMD_BYTE(category, command) \
+ (((category) << 4) | ((command) << 1))
+
+
+typedef enum {
+ GOODIX_TRANSPORT_IDLE,
+ GOODIX_TRANSPORT_SEND,
+ GOODIX_TRANSPORT_ACK,
+ GOODIX_TRANSPORT_RESPONSE,
+ GOODIX_TRANSPORT_EVENT,
+ GOODIX_TRANSPORT_REPLY,
+} GoodixTransportPhase;
+
+/* A command owns its OUT callback and logical wait, never the physical IN. */
+struct _GoodixTransport
+{
+ FpDevice *dev;
+ GoodixTransportPhase phase;
+ GoodixTransportDone done;
+ gpointer data;
+ GCancellable *cancellable;
+ GSource *timer;
+ GSource *cancel_source;
+ guint timeout_ms;
+ gint64 deadline_us;
+ GoodixProfile9FdtWaitMode event_mode;
+ GoodixCmd cmd;
+ /* A raw TLS record to write instead of cmd; it is never ACKed. */
+ GBytes *record;
+ gboolean expect_data;
+ gboolean retry;
+ GoodixResponseSlot response_slot;
+ guint8 ack_status;
+ guint attempt;
+ gboolean write_submitted;
+ guint ack_timeout_ms;
+ guint response_timeout_ms;
+ gsize mcu_length;
+ /* A native read completion dispatches every cell before its owner yields. */
+ gboolean processing_cells;
+ gboolean completion_pending;
+ GError *completion_error;
+};
+
+/* usbinterface 020058/021200: one continuous read, stopped only by a joined
+ * hardware boundary. Sender expiry/capture cancellation leaves it untouched. */
+struct _GoodixReader
+{
+ FpDevice *dev;
+ GCancellable *cancel;
+ gboolean pending;
+ GError *error;
+ GoodixTransportJoined joined;
+ gpointer joined_data;
+};
+
+static void goodix_transport_send (GoodixTransport *operation);
+static void goodix_transport_receive (GoodixTransport *operation, guint timeout);
+static void goodix_transport_complete (GoodixTransport *operation, GError *error);
+static void goodix_reader_start (FpDevice *dev);
+static void goodix_transport_ack (GoodixTransport *operation);
+
+static gboolean
+goodix_transport_is_idle (GoodixTransport *operation)
+{
+ return operation->phase == GOODIX_TRANSPORT_IDLE;
+}
+
+/* Native 018dd8 and its command wrappers. Budgets are nominal milliseconds;
+ * GLib measures elapsed time, rather than Sleep(1)/Wait(50) poll counts.
+ * Register 82 here is the sized/chip adapter (200), not the factory two-byte
+ * adapter (500). Unknown commands retain their existing fallback policy. */
+static const GoodixCommandPolicy command_policies[] = {
+ { 0x32, 500, 0, GOODIX_RESPONSE_NONE, TRUE },
+ { 0x34, 500, 0, GOODIX_RESPONSE_NONE, TRUE },
+ { 0x60, 200, 0, GOODIX_RESPONSE_NONE, TRUE },
+ { 0x36, 500, 500, GOODIX_RESPONSE_MANUAL, TRUE },
+ { 0x90, 500, 500, GOODIX_RESPONSE_CONFIG, TRUE },
+ { 0x00, 500, 0, GOODIX_RESPONSE_NONE, TRUE },
+ { 0xa8, 500, 2000, GOODIX_RESPONSE_SYSTEM, TRUE },
+ { 0x20, 500, 500, GOODIX_RESPONSE_IMAGE, FALSE },
+ { 0xa2, 500, 1000, GOODIX_RESPONSE_SYSTEM, FALSE },
+ { 0x82, 500, 200, GOODIX_RESPONSE_REGISTER, TRUE },
+ { 0xa6, 500, 200, GOODIX_RESPONSE_OTP, TRUE },
+ { 0xe4, 500, 1000, GOODIX_RESPONSE_PRODUCTION, TRUE },
+ { 0xe2, 500, 1000, GOODIX_RESPONSE_PRODUCTION, TRUE },
+ { 0xae, 200, 0, GOODIX_RESPONSE_NONE, FALSE },
+ { 0xd2, 500, 0, GOODIX_RESPONSE_NONE, FALSE },
+};
+
+G_STATIC_ASSERT (GOODIX_RESPONSE_COUNT <= 8);
+
+const GoodixCommandPolicy *
+goodix_cmd_policy (guint8 command)
+{
+ for (guint i = 0; i < G_N_ELEMENTS (command_policies); i++)
+ if (command_policies[i].command == command)
+ return &command_policies[i];
+ return NULL;
+}
+
+/* Checks whether replies for @slot land in the shared response cache, which
+ * the awaited command reads as its own reply. */
+static gboolean
+goodix_response_slot_is_shared (GoodixResponseSlot slot)
+{
+ return slot == GOODIX_RESPONSE_SYSTEM || slot == GOODIX_RESPONSE_REGISTER ||
+ slot == GOODIX_RESPONSE_OTP || slot == GOODIX_RESPONSE_PRODUCTION;
+}
+
+static guint8
+goodix_response_bit (GoodixResponseSlot slot)
+{
+ return slot == GOODIX_RESPONSE_NONE ? 0 : 1u << slot;
+}
+
+static void
+goodix_cmd_set_policy (GoodixTransport *operation)
+{
+ guint8 command = GOODIX_PROTO_CMD_BYTE (operation->cmd.category, operation->cmd.command);
+ const GoodixCommandPolicy *policy = goodix_cmd_policy (command);
+
+ operation->retry = goodix_family (FPI_DEVICE_GOODIX53X5 (operation->dev))->protocol.command_budget (
+ command, operation->expect_data, &operation->ack_timeout_ms, &operation->response_timeout_ms);
+ operation->response_slot = policy && operation->expect_data ?
+ policy->response_slot : GOODIX_RESPONSE_NONE;
+}
+
+static const char *
+goodix_cmd_phase_name (GoodixTransportPhase phase)
+{
+ if (phase == GOODIX_TRANSPORT_SEND)
+ return "send";
+ if (phase == GOODIX_TRANSPORT_ACK)
+ return "ACK";
+ g_assert (phase == GOODIX_TRANSPORT_RESPONSE);
+ return "data";
+}
+
+/* Only a transport timeout or send I/O failure in the first transaction is
+ * recoverable here. Protocol, cancellation, disconnect and ownership errors
+ * keep their existing failure policy. The parent and command owner never
+ * change between attempts. */
+static gboolean
+goodix_cmd_native_zero (GoodixTransportPhase phase, const GError *error)
+{
+ if (g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_TIMED_OUT))
+ return TRUE;
+ if (phase != GOODIX_TRANSPORT_SEND || !error || error->domain != G_USB_DEVICE_ERROR)
+ return FALSE;
+ /* Native maps negative writes to zero. These GUsb codes include transfer
+ * error, endpoint stall and ordinary backend failure. Host preconditions,
+ * cancellation and device loss do not authorize another write. */
+ return error->code == G_USB_DEVICE_ERROR_IO ||
+ error->code == G_USB_DEVICE_ERROR_FAILED ||
+ error->code == G_USB_DEVICE_ERROR_NOT_SUPPORTED ||
+ error->code == G_USB_DEVICE_ERROR_INTERNAL;
+}
+
+/* Returns what @operation sends, for its logs and errors. */
+static gchar *
+goodix_transport_describe (GoodixTransport *operation)
+{
+ if (operation->record)
+ return g_strdup ("TLS record");
+ return g_strdup_printf ("command cat=0x%02x cmd=0x%02x",
+ operation->cmd.category, operation->cmd.command);
+}
+
+static gboolean
+goodix_cmd_retry (GoodixTransport *operation, GError *error)
+{
+ GoodixTransportPhase phase = operation->phase;
+
+ if (!operation->retry || operation->attempt != 1 ||
+ (phase != GOODIX_TRANSPORT_SEND && phase != GOODIX_TRANSPORT_ACK &&
+ !(operation->response_slot != GOODIX_RESPONSE_NONE && phase == GOODIX_TRANSPORT_RESPONSE)) ||
+ !(phase == GOODIX_TRANSPORT_SEND ?
+ (operation->record ? goodix_cmd_native_zero (phase, error) :
+ goodix_family (FPI_DEVICE_GOODIX53X5 (operation->dev))->protocol.retry_write (error)) :
+ g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_TIMED_OUT)))
+ return FALSE;
+
+ g_autofree gchar *what = goodix_transport_describe (operation);
+
+ fp_dbg ("Retrying %s phase=%s attempt=1: %s",
+ what, goodix_cmd_phase_name (phase), error->message);
+ g_error_free (error);
+ goodix_transport_send (operation);
+ return TRUE;
+}
+
+/* Round a positive remaining command budget up to milliseconds. */
+static guint
+goodix_deadline_remaining (gint64 deadline_us)
+{
+ gint64 remaining = deadline_us - g_get_monotonic_time ();
+
+ return remaining > 0 ? (guint) ((remaining + 999) / 1000) : 0;
+}
+
+/* Checks whether @cmd downloads a sensor configuration. */
+static gboolean
+goodix_cmd_is_config_download (const GoodixCmd *cmd)
+{
+ return cmd->category == GOODIX_PROTO_CATEGORY_CONFIG &&
+ cmd->command == GOODIX_PROTO_CMD_CONFIG_DOWNLOAD;
+}
+
+/* Checks whether the family's protocol refuses @cmd, whichever caller asks. */
+static gboolean
+goodix_cmd_refused (FpiDeviceGoodix53x5 *self, const GoodixCmd *cmd)
+{
+ return !goodix_family (self)->protocol.may_send (cmd);
+}
+
+/* Appends @payload to the category-D stream and signals its waiter. */
+void
+goodix_mcu_publish (FpiDeviceGoodix53x5 *self, const guint8 *payload, gsize len)
+{
+ if (!self->mcu_rx)
+ self->mcu_rx = g_byte_array_new ();
+ g_byte_array_append (self->mcu_rx, payload,
+ MIN (len, GOODIX_MCU_RX_SIZE - self->mcu_rx->len));
+ self->mcu_ready = TRUE;
+}
+
+static gboolean
+goodix_validate_ack_for_cmd (FpDevice *dev,
+ GoodixTransport *operation,
+ guint8 *status,
+ GError **error)
+{
+ guint8 category, command;
+ const guint8 *payload;
+ gsize payload_len;
+ guint8 expected_cmd_byte = GOODIX_PROTO_CMD_BYTE (operation->cmd.category,
+ operation->cmd.command);
+
+ if (!goodix_parse_reply (dev, &category, &command,
+ &payload, &payload_len, NULL))
+ {
+ g_set_error_literal (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "Failed to parse ACK");
+ return FALSE;
+ }
+
+ if (category != GOODIX_PROTO_CATEGORY_ACK ||
+ command != GOODIX_PROTO_CMD_ACK ||
+ payload_len < 2)
+ {
+ g_set_error (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "Unexpected ACK: expected cmd_byte=0x%02x, got cat=0x%02x cmd=0x%02x len=%zu",
+ expected_cmd_byte, category, command, payload_len);
+ return FALSE;
+ }
+
+ if (payload[0] != expected_cmd_byte)
+ {
+ g_set_error (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "Unexpected ACK: expected cmd_byte=0x%02x, got ack_cmd=0x%02x flags=0x%02x",
+ expected_cmd_byte, payload[0], payload[1]);
+ return FALSE;
+ }
+
+ *status = payload[1];
+ return TRUE;
+}
+
+/* ========================================================================
+ * USB I/O helpers
+ * ======================================================================== */
+
+static void
+goodix_record_write_failed (FpDevice *dev, gpointer data)
+{
+ GoodixTransport *operation = FPI_DEVICE_GOODIX53X5 (dev)->transport;
+
+ operation->timer = NULL;
+ goodix_transport_complete (operation, g_error_copy (data));
+}
+
+static void
+goodix_tx_cb (FpiUsbTransfer *transfer,
+ FpDevice *dev,
+ gpointer user_data,
+ GError *error)
+{
+ GoodixTransport *operation = user_data;
+ GoodixReader *reader = FPI_DEVICE_GOODIX53X5 (dev)->reader;
+
+ /* TOD's WriteTls sleeps 1 ms after every record write, failed or not. */
+ if (error && operation->record)
+ {
+ operation->timer = fpi_device_add_timeout (dev, 1, goodix_record_write_failed,
+ error, (GDestroyNotify) g_error_free);
+ return;
+ }
+ if (error)
+ {
+ goodix_transport_complete (operation, error);
+ return;
+ }
+
+ operation->phase = GOODIX_TRANSPORT_ACK;
+ if (reader && reader->error)
+ {
+ goodix_transport_complete (operation, g_error_copy (reader->error));
+ return;
+ }
+ /* A TLS record is not a protocol message; the sensor never ACKs it. */
+ if (operation->record)
+ {
+ goodix_transport_complete (operation, NULL);
+ return;
+ }
+ operation->deadline_us = g_get_monotonic_time () + operation->ack_timeout_ms * 1000LL;
+ if ((operation->cmd.category == GOODIX_PROTO_CATEGORY_NOP && operation->cmd.command == 0) ||
+ (operation->cmd.category == GOODIX_PROTO_CATEGORY_SYSTEM && operation->cmd.command == 4))
+ operation->cancellable = g_object_ref (goodix_session_io_cancellable (dev));
+ if (operation->ack_status & GOODIX_PROTO_ACK_FLAG_VALID)
+ goodix_transport_ack (operation);
+ else
+ goodix_transport_receive (operation, operation->ack_timeout_ms);
+}
+
+/* The ACK clock starts after OUT completion. IN stays posted during writes. */
+static void
+goodix_transport_send (GoodixTransport *operation)
+{
+ FpDevice *dev = operation->dev;
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixCmd *cmd = &operation->cmd;
+ gsize msg_len, padded_len;
+ guint8 *msg, *chunked;
+ FpiUsbTransfer *transfer;
+ GCancellable *cancellable;
+
+ operation->phase = GOODIX_TRANSPORT_SEND;
+ operation->attempt++;
+ operation->ack_status = 0;
+ g_clear_pointer (&operation->timer, g_source_destroy);
+ g_clear_pointer (&operation->cancel_source, g_source_destroy);
+ g_clear_object (&operation->cancellable);
+ self->command_response_ready &= ~goodix_response_bit (operation->response_slot);
+
+ if (operation->record)
+ {
+ chunked = goodix_family (self)->link.frame_record (operation->record, &padded_len);
+ }
+ else
+ {
+ msg = goodix_proto_build_message (cmd->category, cmd->command,
+ cmd->payload, cmd->payload_len,
+ cmd->use_checksum, &msg_len);
+ chunked = goodix_family (self)->link.frame (msg, msg_len, &padded_len);
+ g_free (msg);
+ }
+ if (!chunked)
+ {
+ goodix_transport_complete (operation, fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_PROTO, "Message too long to frame"));
+ return;
+ }
+
+ transfer = fpi_usb_transfer_new (dev);
+ fpi_usb_transfer_fill_bulk_full (transfer, goodix_family (self)->link.ep_out,
+ chunked, padded_len, g_free);
+ /* Native writes have no timeout. The selected action or hardware-service
+ * owner supplies cancellation until this callback joins; Linux USB removal
+ * independently completes in-flight transfers with NO_DEVICE.
+ * libfprint completes an already-cancelled submission without starting
+ * it, so only a started write can leave the sensor partially commanded. */
+ cancellable = goodix_session_io_cancellable (dev);
+ operation->write_submitted = !g_cancellable_is_cancelled (cancellable);
+ /* Native D0 entry starts the continuous reader before launching the GTLS
+ * worker. Post IN before the first OUT after quiesce, too, so queued wake
+ * notifications can arrive without waiting for a command submission. */
+ goodix_reader_start (dev);
+ fpi_usb_transfer_submit (transfer, 0, cancellable, goodix_tx_cb, operation);
+}
+
+/* Forward declarations */
+static void goodix_rx_cb (FpiUsbTransfer *transfer,
+ FpDevice *dev,
+ gpointer user_data,
+ GError *error);
+
+static void
+goodix_transport_free (GoodixTransport *operation)
+{
+ g_clear_pointer (&operation->timer, g_source_destroy);
+ g_clear_pointer (&operation->cancel_source, g_source_destroy);
+ g_clear_object (&operation->cancellable);
+ g_clear_error (&operation->completion_error);
+ g_free (operation->cmd.payload);
+ g_clear_pointer (&operation->record, g_bytes_unref);
+ g_object_unref (operation->dev);
+ g_free (operation);
+}
+
+static void
+goodix_transport_expired (FpDevice *dev, gpointer data)
+{
+ GoodixTransport *operation = data;
+
+ operation->timer = NULL;
+ if (operation->phase == GOODIX_TRANSPORT_ACK && operation->expect_data &&
+ goodix_family (FPI_DEVICE_GOODIX53X5 (dev))->protocol.ack_timeout_waits_for_data)
+ {
+ g_autofree gchar *what = goodix_transport_describe (operation);
+
+ fp_dbg ("No ACK for %s; waiting for its data", what);
+ goodix_transport_ack (operation);
+ return;
+ }
+ goodix_transport_complete (operation,
+ g_error_new_literal (G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_TIMED_OUT,
+ "Receive deadline expired"));
+}
+
+static gboolean
+goodix_transport_cancelled (GCancellable *cancel, gpointer data)
+{
+ goodix_transport_complete (data, g_error_new_literal (G_IO_ERROR, G_IO_ERROR_CANCELLED,
+ "Receive wait cancelled"));
+ return G_SOURCE_REMOVE;
+}
+
+static void
+goodix_transport_arm_wait (GoodixTransport *operation)
+{
+ g_clear_pointer (&operation->timer, g_source_destroy);
+ g_clear_pointer (&operation->cancel_source, g_source_destroy);
+ if (operation->deadline_us)
+ operation->timer = fpi_device_add_timeout (operation->dev,
+ goodix_deadline_remaining (operation->deadline_us),
+ goodix_transport_expired, operation, NULL);
+ if (operation->cancellable)
+ {
+ operation->cancel_source = g_cancellable_source_new (operation->cancellable);
+ g_source_set_callback (operation->cancel_source, G_SOURCE_FUNC (goodix_transport_cancelled),
+ operation, NULL);
+ g_source_attach (operation->cancel_source, g_main_context_get_thread_default ());
+ g_source_unref (operation->cancel_source);
+ }
+}
+
+static GoodixTransport *
+goodix_transport_new (FpDevice *dev,
+ GoodixTransportPhase phase,
+ GoodixTransportDone done,
+ gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixTransport *operation = g_new0 (GoodixTransport, 1);
+
+ g_assert (!self->transport);
+ operation->dev = g_object_ref (dev);
+ operation->phase = phase;
+ operation->response_slot = GOODIX_RESPONSE_NONE;
+ operation->done = done;
+ operation->data = data;
+ self->transport = operation;
+ return operation;
+}
+
+/* Consume one coalesced MCU signal, retaining any unread stream suffix. */
+static gboolean
+goodix_transport_take_mcu (GoodixTransport *operation)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (operation->dev);
+ gsize count;
+
+ if (operation->processing_cells ||
+ operation->phase != GOODIX_TRANSPORT_REPLY || !self->mcu_ready)
+ return FALSE;
+
+ count = self->mcu_rx ? self->mcu_rx->len : 0;
+ if (operation->mcu_length)
+ count = MIN (count, operation->mcu_length);
+ g_clear_pointer (&self->mcu_reply, g_bytes_unref);
+ self->mcu_reply = g_bytes_new (count ? self->mcu_rx->data : NULL, count);
+ if (count)
+ g_byte_array_remove_range (self->mcu_rx, 0, count);
+ self->mcu_ready = FALSE;
+ self->reply_valid = TRUE;
+ self->reply_category = 0x0d;
+ self->reply_command = 1;
+ self->reply_payload = g_bytes_get_data (self->mcu_reply, &self->reply_payload_len);
+ goodix_transport_complete (operation, NULL);
+ return TRUE;
+}
+
+/* Command deadlines do not own the continuous receiver's partial packet. */
+static void
+goodix_transport_receive (GoodixTransport *operation, guint timeout)
+{
+ FpDevice *dev = operation->dev;
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (goodix_transport_take_mcu (operation))
+ return;
+ g_clear_pointer (&self->mcu_reply, g_bytes_unref);
+ operation->timeout_ms = timeout;
+ if (!self->rx.len || goodix_proto_rx_complete (&self->rx))
+ goodix_proto_rx_reset (&self->rx);
+ self->reply_valid = FALSE;
+
+ if (operation->processing_cells)
+ return;
+ goodix_transport_arm_wait (operation);
+ goodix_reader_start (dev);
+}
+
+/* A generic response is a view of the shared cache at consumption time, not
+ * the last RX packet (which may be the ACK). Event families can alias command
+ * selectors; expose the awaited selector to existing named reply parsers.
+ * Keep short-packet lengths for Linux validation, and the native production
+ * length prefix, while bounding every view by the owned cache. */
+static GError *
+goodix_transport_select_response (GoodixTransport *operation)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (operation->dev);
+ GoodixResponseSlot slot = operation->response_slot;
+ gsize offset = 0, length;
+
+ if (!goodix_response_slot_is_shared (slot))
+ return NULL;
+ if (!(self->command_response_ready & goodix_response_bit (slot)))
+ return fpi_device_error_new_msg (FP_DEVICE_ERROR_PROTO,
+ "Command response event is unavailable");
+
+ length = self->shared_response_lengths[slot];
+ if (slot == GOODIX_RESPONSE_PRODUCTION)
+ {
+ guint32 wire_length;
+ memcpy (&wire_length, self->shared_response_storage, sizeof (wire_length));
+ length = GUINT32_FROM_LE (wire_length);
+ offset = sizeof (wire_length);
+ }
+ if (length > sizeof (self->shared_response_storage) - offset)
+ return fpi_device_error_new_msg (FP_DEVICE_ERROR_PROTO,
+ "Shared response length exceeds cache capacity");
+
+ self->reply_valid = TRUE;
+ self->reply_category = operation->cmd.category;
+ self->reply_command = operation->cmd.command;
+ self->reply_payload = self->shared_response_storage + offset;
+ self->reply_payload_len = length;
+ return NULL;
+}
+
+static void
+goodix_transport_complete (GoodixTransport *operation, GError *error)
+{
+ /* Completion can free this owner and submit the next command. Drain the
+ * completed USB buffer first, including packets after its ACK or response. */
+ if (operation->processing_cells)
+ {
+ operation->completion_pending = TRUE;
+ if (!operation->completion_error)
+ operation->completion_error = error;
+ else
+ g_clear_error (&error);
+ return;
+ }
+ g_autoptr(FpDevice) dev = g_object_ref (operation->dev);
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixTransportDone done = operation->done;
+ gpointer data = operation->data;
+ gboolean image_failed = !error && operation->response_slot == GOODIX_RESPONSE_IMAGE &&
+ self->image_response_failed &&
+ (operation->phase == GOODIX_TRANSPORT_ACK ||
+ operation->phase == GOODIX_TRANSPORT_RESPONSE);
+ gboolean config_failed = !error && operation->expect_data &&
+ goodix_cmd_is_config_download (&operation->cmd) &&
+ self->config_download_failed;
+
+ if (image_failed)
+ error = g_error_new_literal (G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_IO,
+ "Image receiver rejected the frame");
+ if (config_failed)
+ error = fpi_device_error_new_msg (FP_DEVICE_ERROR_PROTO,
+ "Configuration download failed: status %u",
+ self->config_download_status);
+ if (!error && operation->expect_data &&
+ (operation->phase == GOODIX_TRANSPORT_ACK || operation->phase == GOODIX_TRANSPORT_RESPONSE))
+ error = goodix_transport_select_response (operation);
+ GoodixTransportResult result = {
+ .ack_status = operation->ack_status,
+ .restart_gtls = operation->phase == GOODIX_TRANSPORT_EVENT && self->gtls_restart_pending,
+ .ordinary_exhaustion = error && !(self->reader && self->reader->error) &&
+ (image_failed || config_failed || goodix_cmd_native_zero (operation->phase, error)),
+ .write_cancelled = operation->phase == GOODIX_TRANSPORT_SEND &&
+ operation->write_submitted &&
+ (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED) ||
+ g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_CANCELLED)),
+ };
+
+ if (error && !(self->reader && self->reader->error) && goodix_cmd_retry (operation, error))
+ return;
+ else if (error && operation->attempt)
+ {
+ g_autofree gchar *what = goodix_transport_describe (operation);
+
+ what[0] = g_ascii_toupper (what[0]);
+ g_prefix_error (&error, "%s phase=%s attempt=%u: ", what,
+ goodix_cmd_phase_name (operation->phase), operation->attempt);
+ }
+
+ if (!error && operation->expect_data && goodix_cmd_is_config_download (&operation->cmd) &&
+ !self->config_restore_pending)
+ self->config_lost = FALSE;
+ self->transport = NULL;
+ goodix_transport_free (operation);
+ if (done)
+ done (dev, &result, error, data);
+}
+
+static void
+goodix_rx_continue (GoodixTransport *operation)
+{
+ FpDevice *dev = operation->dev;
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (self->rx.len == 0)
+ {
+ self->rx_idle_partial = FALSE;
+ self->reply_valid = FALSE;
+ }
+ if (operation->processing_cells)
+ return;
+ goodix_transport_arm_wait (operation);
+}
+
+static void
+goodix_transport_ack (GoodixTransport *operation)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (operation->dev);
+
+ if (!operation->expect_data ||
+ (goodix_response_bit (operation->response_slot) & self->command_response_ready))
+ goodix_transport_complete (operation, NULL);
+ else
+ {
+ operation->phase = GOODIX_TRANSPORT_RESPONSE;
+ operation->deadline_us = g_get_monotonic_time () + operation->response_timeout_ms * 1000LL;
+ g_clear_object (&operation->cancellable);
+ if (operation->cmd.category == GOODIX_PROTO_CATEGORY_SYSTEM && operation->cmd.command == 4)
+ operation->cancellable = g_object_ref (goodix_session_io_cancellable (operation->dev));
+ goodix_transport_receive (operation, operation->response_timeout_ms);
+ }
+}
+
+/* Checks whether a reply for @slot answers another command than the one in
+ * flight, as the family's protocol decides. A stale firmware reply must not
+ * complete a reset that shares its slot. */
+static gboolean
+goodix_reply_is_foreign (FpiDeviceGoodix53x5 *self, GoodixResponseSlot slot,
+ guint8 category, guint8 command)
+{
+ GoodixTransport *operation = self->transport;
+
+ return operation && !operation->record &&
+ (operation->phase == GOODIX_TRANSPORT_SEND || operation->phase == GOODIX_TRANSPORT_ACK ||
+ operation->phase == GOODIX_TRANSPORT_RESPONSE) &&
+ (goodix_response_slot_is_shared (slot) ||
+ (slot == GOODIX_RESPONSE_CONFIG && goodix_cmd_is_config_download (&operation->cmd))) &&
+ !goodix_family (self)->protocol.reply_answers (category, command, &operation->cmd);
+}
+
+/* Each sensor request owns a new session followed by a finger-down arm. */
+static void
+goodix_request_reconnect (FpiDeviceGoodix53x5 *self)
+{
+ fp_info ("Sensor requested a new %s session", goodix_family (self)->channel.name);
+ self->reconnect_pending++;
+ self->gtls_restart_pending = TRUE;
+}
+
+void
+goodix_rx_cell (GoodixTransport *operation,
+ const guint8 *buffer,
+ gsize cell_length)
+{
+ FpDevice *dev = operation->dev;
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GError *error = NULL;
+ gboolean fixed_deadline = operation->phase == GOODIX_TRANSPORT_ACK ||
+ (operation->phase == GOODIX_TRANSPORT_RESPONSE && operation->response_slot != GOODIX_RESPONSE_NONE) ||
+ (operation->phase == GOODIX_TRANSPORT_REPLY && operation->mcu_length);
+
+ /* Bounded command polling retains its deadline. Other receives keep the existing
+ * zero-length-read timeout policy. */
+ if (cell_length == 0)
+ {
+ if (!fixed_deadline)
+ operation->deadline_us = operation->timeout_ms ?
+ g_get_monotonic_time () + operation->timeout_ms * 1000LL : 0;
+ goto receive_more;
+ }
+
+ /* Native reassembly restarts on a first cell or a different selector;
+ * orphan continuations are ignored. This also permits an ACK to interrupt
+ * a partial reply retained across a command timeout. */
+ if (!(buffer[0] & 1) ||
+ (buffer[0] & 0xfe) != self->rx.cmd_byte)
+ {
+ goodix_proto_rx_reset (&self->rx);
+ self->rx_idle_partial = FALSE;
+ }
+ if (!self->rx.len && (buffer[0] & 1))
+ goto receive_more;
+
+ if (!goodix_proto_rx_feed_chunk (&self->rx, buffer, cell_length))
+ {
+ error = fpi_device_error_new_msg (FP_DEVICE_ERROR_PROTO,
+ "Protocol reassembly error");
+ goto protocol_error;
+ }
+
+ if (goodix_proto_rx_complete (&self->rx))
+ {
+ gboolean idle_packet = goodix_transport_is_idle (operation) ||
+ operation->completion_pending;
+ GoodixTransport *current = !idle_packet &&
+ (operation->phase == GOODIX_TRANSPORT_ACK || operation->phase == GOODIX_TRANSPORT_RESPONSE)
+ ? operation : NULL;
+ gboolean ack_wait = current && operation->phase == GOODIX_TRANSPORT_ACK;
+
+ self->reply_valid = goodix_proto_rx_parse (
+ &self->rx, &self->reply_category, &self->reply_command,
+ &self->reply_payload, &self->reply_payload_len);
+ guint8 category = self->reply_category, command = self->reply_command;
+ const guint8 *payload = self->reply_payload;
+ gsize payload_len = self->reply_payload_len;
+ gboolean ack_packet = self->reply_valid && category == GOODIX_PROTO_CATEGORY_ACK &&
+ command == GOODIX_PROTO_CMD_ACK && payload_len >= 2;
+ gboolean expected_ack = ack_packet && ack_wait && payload[0] ==
+ GOODIX_PROTO_CMD_BYTE (current->cmd.category, current->cmd.command);
+
+ /* ACK slots are written even before the OUT callback returns. Only the
+ * addressed sender clears/observes its slot; no command-generation tag. */
+ if (ack_packet && self->transport &&
+ payload[0] == GOODIX_PROTO_CMD_BYTE (self->transport->cmd.category,
+ self->transport->cmd.command))
+ self->transport->ack_status = payload[1];
+ /* Only 533c reports events; goodix_htsec_event always returns NONE. */
+ if (self->reply_valid)
+ switch (goodix_family (self)->protocol.event (category, command, payload, payload_len))
+ {
+ case GOODIX_SENSOR_EVENT_CONFIG_LOST:
+ if (!self->config_lost)
+ fp_info ("ACK for 0x%02x reports lost configuration", payload[0]);
+ if (goodix_family (self)->channel.config_lost)
+ goodix_family (self)->channel.config_lost (self);
+ self->config_lost = TRUE;
+ if (!self->config_restore_active)
+ self->config_restore_pending = TRUE;
+ /* A scan waiting for a finger restores the configuration first. */
+ if (operation->phase == GOODIX_TRANSPORT_EVENT)
+ {
+ goodix_proto_rx_reset (&self->rx);
+ goodix_transport_complete (operation, NULL);
+ return;
+ }
+ break;
+ case GOODIX_SENSOR_EVENT_RECONNECT:
+ goodix_request_reconnect (self);
+ goodix_proto_rx_reset (&self->rx);
+ if (operation->phase == GOODIX_TRANSPORT_EVENT)
+ goodix_transport_complete (operation, NULL);
+ else
+ goto receive_more;
+ return;
+ case GOODIX_SENSOR_EVENT_NONE:
+ break;
+ }
+
+ if (self->reply_valid)
+ {
+ if (category == GOODIX_PROTO_CATEGORY_NOTICE)
+ {
+ /* Notice publication shares the worker's coalescing slot, but
+ * never supplies a raw FDT vector or mutates FDT bases. */
+ gboolean published = command == 1 ||
+ (command == 0 && goodix_family (self)->protocol.notice_irq (self, payload, payload_len));
+
+ if (published)
+ {
+ self->pending_fdt.type = command == 0 ?
+ GOODIX_FDT_EVENT_ESD : GOODIX_FDT_EVENT_WAKE;
+ self->pending_fdt.event.pending = TRUE;
+ }
+ goodix_proto_rx_reset (&self->rx);
+ if (published && operation->phase == GOODIX_TRANSPORT_EVENT)
+ goodix_transport_complete (operation, NULL);
+ else
+ goto receive_more;
+ return;
+ }
+ if (category == GOODIX_PROTO_CATEGORY_IMAGE)
+ {
+ gboolean completed = goodix_rx_image (operation, payload, payload_len);
+
+ goodix_proto_rx_reset (&self->rx);
+ if (!completed)
+ goto receive_more;
+ return;
+ }
+ if (category == GOODIX_PROTO_CATEGORY_MCU)
+ {
+ /* Parser publication is independent of command, ACK, and GTLS
+ * state. Preserve the native bounded byte stream and event. */
+ goodix_mcu_publish (self, payload, payload_len);
+ goodix_proto_rx_reset (&self->rx);
+ if (goodix_transport_take_mcu (operation))
+ return;
+ goto receive_more;
+ }
+ GoodixResponseSlot slot =
+ category == GOODIX_PROTO_CATEGORY_FDT && command == GOODIX_PROTO_CMD_FDT_MANUAL ?
+ GOODIX_RESPONSE_MANUAL :
+ category == GOODIX_PROTO_CATEGORY_CONFIG ? GOODIX_RESPONSE_CONFIG :
+ category == GOODIX_PROTO_CATEGORY_SYSTEM && (command == 0 || command == 1 || command == 4) ?
+ GOODIX_RESPONSE_SYSTEM :
+ category == GOODIX_PROTO_CATEGORY_REGISTER ? GOODIX_RESPONSE_REGISTER :
+ category == GOODIX_PROTO_CATEGORY_SYSTEM && command == 3 ? GOODIX_RESPONSE_OTP :
+ category == GOODIX_PROTO_CATEGORY_FIRMWARE ? GOODIX_RESPONSE_FIRMWARE :
+ category == GOODIX_PROTO_CATEGORY_PRODUCTION ? GOODIX_RESPONSE_PRODUCTION :
+ GOODIX_RESPONSE_NONE;
+ gboolean shared = goodix_response_slot_is_shared (slot) ||
+ category == GOODIX_PROTO_CATEGORY_FIRMWARE;
+
+ if (goodix_reply_is_foreign (self, slot, category, command))
+ {
+ fp_dbg ("Ignoring a cat=0x%02x cmd=0x%02x reply while cat=0x%02x cmd=0x%02x waits",
+ category, command, self->transport->cmd.category,
+ self->transport->cmd.command);
+ goodix_proto_rx_reset (&self->rx);
+ goto receive_more;
+ }
+ if ((category == GOODIX_PROTO_CATEGORY_FIRMWARE ||
+ (category == GOODIX_PROTO_CATEGORY_CONFIG && command == 2)) && !payload_len)
+ {
+ error = fpi_device_error_new_msg (FP_DEVICE_ERROR_PROTO,
+ "Status reply is too short");
+ goto protocol_error;
+ }
+ if (category == GOODIX_PROTO_CATEGORY_CONFIG && command == 2)
+ self->config_response_status = payload[0];
+ if (category == GOODIX_PROTO_CATEGORY_CONFIG && command == GOODIX_PROTO_CMD_CONFIG_DOWNLOAD)
+ {
+ self->config_download_status = payload_len ? payload[0] : 0;
+ self->config_download_failed =
+ !goodix_family (self)->protocol.download_succeeded (payload, payload_len);
+ }
+
+ /* DataFromDevice publishes these shared stores without a matching
+ * command. Only A/0, A/1 and A/4 signal the version getter's event.
+ * Retain every unwritten suffix, including beyond the firmware view. */
+ if (shared)
+ {
+ gsize offset = category == GOODIX_PROTO_CATEGORY_PRODUCTION ? 4 : 0;
+ gsize count = category == GOODIX_PROTO_CATEGORY_FIRMWARE ? MIN (payload_len, 1) :
+ MIN (payload_len, sizeof (self->shared_response_storage) - offset);
+
+ if (category == GOODIX_PROTO_CATEGORY_PRODUCTION)
+ {
+ guint32 length = GUINT32_TO_LE ((guint32) payload_len);
+ memcpy (self->shared_response_storage, &length, sizeof (length));
+ }
+ memcpy (self->shared_response_storage + offset, payload, count);
+ if (slot != GOODIX_RESPONSE_NONE)
+ self->shared_response_lengths[slot] = payload_len;
+ }
+
+ if (slot != GOODIX_RESPONSE_NONE)
+ {
+ if (slot == GOODIX_RESPONSE_MANUAL)
+ {
+ if (payload_len < sizeof (self->manual_response))
+ {
+ error = fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_PROTO, "Manual FDT reply is too short");
+ goto protocol_error;
+ }
+ memcpy (self->manual_response, payload, sizeof (self->manual_response));
+ }
+ /* Native 01a7ec publishes response events independently of the
+ * waiter. Every category-9 command signals configuration; its
+ * command-2 status does not decide download success. Category F
+ * signals the separate firmware event after its shared-byte copy. */
+ self->command_response_ready |= goodix_response_bit (slot);
+ if (!current || operation->phase != GOODIX_TRANSPORT_RESPONSE ||
+ current->response_slot != slot)
+ {
+ goodix_proto_rx_reset (&self->rx);
+ goto receive_more;
+ }
+ goodix_transport_complete (operation, NULL);
+ return;
+ }
+ else if (category == GOODIX_PROTO_CATEGORY_FDT &&
+ (command == GOODIX_PROTO_CMD_FDT_DOWN || command == GOODIX_PROTO_CMD_FDT_UP))
+ {
+ GoodixFdtEventType type;
+ GoodixProfile9FdtEvent event;
+ g_autoptr(GError) event_error = NULL;
+ GoodixProfile9FdtWaitMode mode = command == GOODIX_PROTO_CMD_FDT_DOWN ?
+ GOODIX_PROFILE9_FDT_WAIT_DOWN : GOODIX_PROFILE9_FDT_WAIT_UP;
+
+ if (!goodix_cmd_parse_fdt_event (dev, mode, &type, &event, &event_error))
+ {
+ error = g_steal_pointer (&event_error);
+ goto protocol_error;
+ }
+ /* Every native parser mutation precedes replacement of the
+ * latest worker notification, including during config/manual. */
+ if (!event.pending)
+ {
+ goodix_proto_rx_reset (&self->rx);
+ goto receive_more;
+ }
+ goodix_recv_apply_fdt_event (dev, type, &event);
+ if (type != GOODIX_FDT_EVENT_CONFIG)
+ self->pending_fdt.event = event;
+ self->pending_fdt.event.pending = TRUE;
+ self->pending_fdt.type = type;
+ goodix_proto_rx_reset (&self->rx);
+ if (operation->phase == GOODIX_TRANSPORT_EVENT)
+ {
+ goodix_transport_complete (operation, NULL);
+ return;
+ }
+ goto receive_more;
+ }
+ if (idle_packet)
+ {
+ /* No active waiter: ordinary unclaimed packets have no result
+ * owner. EC data likewise has no native cache/event side effect. */
+ fp_dbg ("Idle receive consumed cat=0x%02x cmd=0x%02x", category, command);
+ goodix_proto_rx_reset (&self->rx);
+ goto receive_more;
+ }
+ }
+ else
+ {
+ /* Native checksum rejection publishes nothing and continues reading. */
+ goodix_proto_rx_reset (&self->rx);
+ goto receive_more;
+ }
+
+ /* Native updates independent ACK slots. Only the command being polled
+ * consumes its status; unrelated ACKs never fail or satisfy that wait. */
+ if (ack_packet && !expected_ack)
+ {
+ goodix_proto_rx_reset (&self->rx);
+ goto receive_more;
+ }
+ if (ack_wait && category == GOODIX_PROTO_CATEGORY_ACK &&
+ command == GOODIX_PROTO_CMD_ACK)
+ {
+ guint8 status;
+
+ if (!goodix_validate_ack_for_cmd (dev, current, &status, &error))
+ goodix_transport_complete (operation, error);
+ /* Even status preserves this attempt's
+ * original ACK deadline. Only exhaustion permits a retry. */
+ else if (!(status & GOODIX_PROTO_ACK_FLAG_VALID))
+ {
+ goodix_proto_rx_reset (&self->rx);
+ goto receive_more;
+ }
+ else
+ {
+ current->ack_status = status;
+ goodix_transport_ack (operation);
+ }
+ return;
+ }
+ /* A complete packet is not evidence that this waiter completed. Native
+ * unclaimed families/subcommands publish nothing; passive responses above
+ * publish only their own event. Keep ACK/data/MCU/FDT waits and their clocks
+ * intact, including for notifications without a consumer in this layer. */
+ goodix_proto_rx_reset (&self->rx);
+ goto receive_more;
+ }
+ else
+ {
+ /* Preserve unrelated per-continuation data budgets. Scoped command waits
+ * keep one deadline across interleaved packets and continuations. */
+ if (!fixed_deadline && !goodix_transport_is_idle (operation) &&
+ !(operation->phase == GOODIX_TRANSPORT_EVENT && self->service_active))
+ operation->deadline_us = g_get_monotonic_time () + GOODIX_DATA_TIMEOUT * 1000LL;
+ goto receive_more;
+ }
+ return;
+
+protocol_error:
+ goodix_transport_complete (operation, error);
+ return;
+
+receive_more:
+ goodix_rx_continue (operation);
+}
+
+/* Requests a secure-channel restart when the family's channel needs one for
+ * an undecodable frame. An error during a restart still counts. */
+static void
+goodix_count_image_error (FpiDeviceGoodix53x5 *self)
+{
+ if (!goodix_family (self)->channel.image_error (self))
+ return;
+ if (!self->gtls_restart_active)
+ self->gtls_restart_pending = TRUE;
+}
+
+/* Checks whether @operation is a command waiting for its image response. */
+static gboolean
+goodix_transport_awaits_image (GoodixTransport *operation)
+{
+ return !goodix_transport_is_idle (operation) && !operation->completion_pending &&
+ operation->phase == GOODIX_TRANSPORT_RESPONSE &&
+ operation->response_slot == GOODIX_RESPONSE_IMAGE;
+}
+
+/* Publishes an encrypted frame as the image response and returns TRUE if
+ * that completed @operation. */
+gboolean
+goodix_rx_image (GoodixTransport *operation, const guint8 *payload, gsize len)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (operation->dev);
+ g_autofree guint8 *decoded = NULL;
+ gsize decoded_len = 0;
+ GoodixFrameStatus status = goodix_family (self)->channel.decrypt_frame (
+ self, payload, len, &decoded, &decoded_len);
+ guint16 *frame = status == GOODIX_FRAME_DECRYPTED ?
+ goodix_device_decode_image (decoded, decoded_len) : NULL;
+
+ /* The native raw callback authenticates, converts and signals
+ * before the sender consumes ACK. Failed authentication leaves
+ * the counter/cache intact; an authenticated bad frame retains
+ * the advanced counter but does not signal readiness. */
+ if (frame)
+ {
+ g_free (self->image_response);
+ self->image_response = frame;
+ self->image_response_failed = FALSE;
+ self->command_response_ready |= goodix_response_bit (GOODIX_RESPONSE_IMAGE);
+ }
+ else if (status != GOODIX_FRAME_REJECTED)
+ {
+ /* Incomplete-session rejection consumes the counter but preserves raw
+ * status; an established frame failing to decrypt or decode sets it. */
+ self->image_response_failed = TRUE;
+ }
+ if (!frame && status != GOODIX_FRAME_INVALID)
+ goodix_count_image_error (self);
+
+ if (operation->phase == GOODIX_TRANSPORT_EVENT && self->gtls_restart_pending)
+ {
+ goodix_transport_complete (operation, NULL);
+ return TRUE;
+ }
+ if (goodix_transport_awaits_image (operation) &&
+ (self->command_response_ready & goodix_response_bit (GOODIX_RESPONSE_IMAGE)))
+ {
+ goodix_transport_complete (operation, NULL);
+ return TRUE;
+ }
+ return FALSE;
+}
+
+/* Drops the partial frame the family's link keeps for the next transfer. */
+static void
+goodix_link_discard (FpiDeviceGoodix53x5 *self)
+{
+ const GoodixLink *link = &goodix_family (self)->link;
+
+ if (link->discard)
+ link->discard (self);
+}
+
+static void
+goodix_reader_joined (GoodixReader *reader)
+{
+ g_autoptr(FpDevice) dev = reader->dev;
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixTransportJoined joined = reader->joined;
+ gpointer data = reader->joined_data;
+
+ g_assert (!reader->pending);
+ self->reader = NULL;
+ /* The next reader starts a new stream: a partial pack cannot continue. */
+ goodix_link_discard (self);
+ g_clear_object (&reader->cancel);
+ g_clear_error (&reader->error);
+ g_free (reader);
+ if (joined)
+ joined (dev, data);
+}
+
+static void
+goodix_reader_start (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixReader *reader = self->reader;
+ FpiUsbTransfer *transfer;
+
+ if (!reader)
+ {
+ reader = self->reader = g_new0 (GoodixReader, 1);
+ reader->dev = g_object_ref (dev);
+ reader->cancel = g_cancellable_new ();
+ }
+ if (reader->pending || reader->joined || reader->error)
+ return;
+ reader->pending = TRUE;
+ transfer = fpi_usb_transfer_new (dev);
+ fpi_usb_transfer_fill_bulk (transfer, goodix_family (self)->link.ep_in,
+ GOODIX_USB_READ_SIZE);
+ fpi_usb_transfer_submit (transfer, 0, reader->cancel, goodix_rx_cb, reader);
+}
+
+static void
+goodix_rx_cb (FpiUsbTransfer *transfer,
+ FpDevice *dev,
+ gpointer user_data,
+ GError *error)
+{
+ GoodixReader *reader = user_data;
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixTransport idle = { .dev = dev, .phase = GOODIX_TRANSPORT_IDLE,
+ .response_slot = GOODIX_RESPONSE_NONE };
+ GoodixTransport *operation = self->transport;
+
+ reader->pending = FALSE;
+ if (!operation || operation->phase == GOODIX_TRANSPORT_SEND)
+ operation = &idle;
+
+ if (error)
+ {
+ if (reader->joined)
+ {
+ g_clear_error (&error);
+ goodix_reader_joined (reader);
+ return;
+ }
+ /* WDF requests pipe reset/restart here. GUsb has no corresponding pipe
+ * reset API; retain the failure until joined hardware reconstruction.
+ * Never disguise a physical failure as sender timeout/retry. */
+ reader->error = error;
+ self->needs_reinit = TRUE;
+ /* The lost transfer leaves no way to find the next pack header. */
+ goodix_link_discard (self);
+ if (operation != &idle)
+ goodix_transport_complete (operation, g_error_copy (error));
+ return;
+ }
+
+ operation->processing_cells = TRUE;
+ goodix_family (self)->link.receive (self, operation, transfer->buffer,
+ transfer->actual_length);
+ operation->processing_cells = FALSE;
+ self->rx_idle_partial = self->rx.len && !goodix_proto_rx_complete (&self->rx);
+
+ if (reader->joined)
+ {
+ g_clear_error (&idle.completion_error);
+ goodix_reader_joined (reader);
+ return;
+ }
+ goodix_reader_start (dev);
+ if (operation == &idle)
+ {
+ g_clear_error (&idle.completion_error);
+ return;
+ }
+
+ /* Category-D packets in this completion share one stream/event. Select the
+ * caller's bounded view once, after every publication, not once per cell. */
+ if (!operation->completion_error && goodix_transport_take_mcu (operation))
+ return;
+ if (operation->completion_pending)
+ {
+ operation->completion_pending = FALSE;
+ goodix_transport_complete (operation, g_steal_pointer (&operation->completion_error));
+ return;
+ }
+ /* Empty completions retain the existing timeout policy; draining a nonempty
+ * batch must not look like a fresh zero-byte completion or renew its budget. */
+ if (transfer->actual_length == 0)
+ goodix_rx_cell (operation, NULL, 0);
+ else
+ goodix_rx_continue (operation);
+}
+
+void
+goodix_transport_reset_mcu (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ g_assert (!self->transport);
+ if (self->mcu_rx)
+ g_byte_array_set_size (self->mcu_rx, 0);
+ g_clear_pointer (&self->mcu_reply, g_bytes_unref);
+ self->reply_valid = FALSE;
+ /* A pack cut short by the previous channel never completes. */
+ goodix_link_discard (self);
+ /* The native attempt resets ring indices, not the auto-reset event. */
+}
+
+void
+goodix_transport_invalidate (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ g_assert (!self->transport);
+ g_assert (!self->reader);
+ g_clear_pointer (&self->mcu_rx, g_byte_array_unref);
+ g_clear_pointer (&self->mcu_reply, g_bytes_unref);
+ self->mcu_ready = FALSE;
+ g_clear_pointer (&self->image_response, g_free);
+ self->image_response_failed = FALSE;
+ self->image_error_history = FALSE;
+ self->gtls_restart_pending = FALSE;
+ self->reconnect_requested = FALSE;
+ self->reconnect_pending = 0;
+ /* psk_refresh_pending survives: the sensor stays unkeyed across a suspend
+ * until the refresh runs, as the vendor's Stop keeps its flag for Start. */
+ self->command_response_ready &= ~goodix_response_bit (GOODIX_RESPONSE_IMAGE);
+ if (self->rx.buf)
+ goodix_proto_rx_reset (&self->rx);
+ goodix_link_discard (self);
+ self->reply_valid = FALSE;
+ self->rx_idle_partial = FALSE;
+ self->pending_fdt.event.pending = FALSE;
+ /* Joined cold teardown retires the HAL mode owner, not an ordinary reader
+ * stop, command completion, FDT rearm or coordinator handoff. */
+ self->requested_mode = GOODIX_REQUESTED_MODE_CAPTURE;
+}
+
+gboolean
+goodix_recv_select_fdt (FpDevice *dev, GoodixFdtEventType *type,
+ GoodixProfile9FdtEvent *event,
+ guint16 *prior_down, GError **error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixFdtNotification *pending = &self->pending_fdt;
+
+ g_assert (!self->transport);
+ if (pending->event.pending)
+ {
+ *type = pending->type;
+ if (*type == GOODIX_FDT_EVENT_DOWN || *type == GOODIX_FDT_EVENT_UP ||
+ *type == GOODIX_FDT_EVENT_REVERSE)
+ *event = pending->event;
+ event->pending = TRUE;
+ if (*type == GOODIX_FDT_EVENT_REVERSE)
+ {
+ /* 014480 calls 0053b0 at handler execution. Reference publication
+ * can replace this shared manual/prior store after packet reception;
+ * only the selected handler's local operands become immutable. */
+ for (guint i = 0; i < GOODIX_PROFILE9_FDT_AREA_COUNT; i++)
+ prior_down[i] = self->profile9_fdt.base_manual[i * 2 + 1];
+ }
+ pending->event.pending = FALSE;
+ return TRUE;
+ }
+ g_set_error_literal (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "No completed FDT event");
+ return FALSE;
+}
+
+void
+goodix_recv_apply_fdt_event (FpDevice *dev,
+ GoodixFdtEventType type,
+ const GoodixProfile9FdtEvent *event)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixProfile9FdtState *fdt = &self->profile9_fdt;
+
+ if (type != GOODIX_FDT_EVENT_DOWN && type != GOODIX_FDT_EVENT_UP &&
+ type != GOODIX_FDT_EVENT_REVERSE)
+ return;
+ if (type == GOODIX_FDT_EVENT_DOWN)
+ {
+ goodix_device_generate_fdt_up_base (event->raw, event->touch_flag,
+ &self->calib, fdt->base_up);
+ }
+ else
+ {
+ if (type == GOODIX_FDT_EVENT_REVERSE)
+ {
+ for (guint i = 0; i < GOODIX_PROFILE9_FDT_AREA_COUNT; i++)
+ self->fdt_prior_down[i] = fdt->base_down[i * 2 + 1];
+ memcpy (fdt->base_manual, fdt->base_down, sizeof (fdt->base_manual));
+ }
+ goodix_device_generate_fdt_base (event->raw, GOODIX_FDT_BASE_LEN,
+ fdt->base_down);
+ }
+}
+
+/* Completes @done with a busy error, returning TRUE, if another transport
+ * operation or a reader join owns the device. */
+static gboolean
+goodix_transport_reject_busy (FpDevice *dev, GoodixTransportDone done, gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixTransportResult result = {0};
+
+ if (!self->transport && !(self->reader && self->reader->joined))
+ return FALSE;
+ done (dev, &result, fpi_device_error_new_msg (FP_DEVICE_ERROR_BUSY,
+ "A device transport operation is already active"), data);
+ return TRUE;
+}
+
+void
+goodix_transport_command (FpDevice *dev,
+ const GoodixTransportRequest *request,
+ GoodixTransportDone done,
+ gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixTransport *operation;
+
+ if (goodix_transport_reject_busy (dev, done, data))
+ return;
+
+ if (goodix_cmd_refused (self, &request->cmd))
+ {
+ GoodixTransportResult result = {0};
+ done (dev, &result, fpi_device_error_new_msg (FP_DEVICE_ERROR_NOT_SUPPORTED,
+ "Refusing to write to this sensor: it is never provisioned"), data);
+ return;
+ }
+
+ operation = goodix_transport_new (dev, GOODIX_TRANSPORT_SEND, done, data);
+ operation->done = done;
+ operation->data = data;
+ operation->cmd = request->cmd;
+ operation->cmd.payload = request->cmd.payload_len ?
+ g_memdup2 (request->cmd.payload, request->cmd.payload_len) : NULL;
+ operation->expect_data = request->expect_data;
+ goodix_cmd_set_policy (operation);
+
+ goodix_transport_send (operation);
+}
+
+void
+goodix_transport_send_record (FpDevice *dev,
+ GBytes *record,
+ GoodixTransportDone done,
+ gpointer data)
+{
+ GoodixTransport *operation;
+
+ if (goodix_transport_reject_busy (dev, done, data))
+ return;
+ if (!goodix_family (FPI_DEVICE_GOODIX53X5 (dev))->link.frame_record)
+ {
+ GoodixTransportResult result = {0};
+ done (dev, &result, fpi_device_error_new_msg (FP_DEVICE_ERROR_NOT_SUPPORTED,
+ "This sensor has no TLS channel"), data);
+ return;
+ }
+
+ operation = goodix_transport_new (dev, GOODIX_TRANSPORT_SEND, done, data);
+ operation->record = g_bytes_ref (record);
+ goodix_transport_send (operation);
+}
+
+static void
+goodix_transport_wait (FpDevice *dev,
+ GoodixTransportPhase phase,
+ guint timeout,
+ gsize mcu_length,
+ GoodixProfile9FdtWaitMode mode,
+ GoodixTransportDone done,
+ gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixTransport *operation;
+
+ if (goodix_transport_reject_busy (dev, done, data))
+ return;
+ operation = goodix_transport_new (dev, phase, done, data);
+ if (self->reader && self->reader->error)
+ {
+ goodix_transport_complete (operation, g_error_copy (self->reader->error));
+ return;
+ }
+ operation->mcu_length = mcu_length;
+ operation->event_mode = mode;
+ operation->deadline_us = timeout ? g_get_monotonic_time () + timeout * 1000LL : 0;
+ if (phase == GOODIX_TRANSPORT_EVENT)
+ {
+ operation->cancellable = g_cancellable_new ();
+ if (self->pending_fdt.event.pending || self->gtls_restart_pending)
+ {
+ goodix_transport_complete (operation, NULL);
+ return;
+ }
+ }
+ goodix_transport_receive (operation, timeout);
+}
+
+void
+goodix_transport_wait_event (FpDevice *dev,
+ GoodixProfile9FdtWaitMode mode,
+ GoodixTransportDone done,
+ gpointer data)
+{
+ goodix_transport_wait (dev, GOODIX_TRANSPORT_EVENT, 0, 0, mode, done, data);
+}
+
+void
+goodix_transport_wait_mcu (FpDevice *dev,
+ guint timeout,
+ gsize length,
+ GoodixTransportDone done,
+ gpointer data)
+{
+ goodix_transport_wait (dev, GOODIX_TRANSPORT_REPLY, timeout, length,
+ GOODIX_PROFILE9_FDT_WAIT_NONE, done, data);
+}
+
+void
+goodix_transport_cancel_event (FpDevice *dev)
+{
+ GoodixTransport *operation = FPI_DEVICE_GOODIX53X5 (dev)->transport;
+
+ if (operation && operation->phase == GOODIX_TRANSPORT_EVENT)
+ g_cancellable_cancel (operation->cancellable);
+}
+
+void
+goodix_transport_quiesce (FpDevice *dev,
+ GoodixTransportJoined joined,
+ gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixReader *reader = self->reader;
+
+ g_assert (!self->transport);
+ if (!reader)
+ {
+ joined (dev, data);
+ return;
+ }
+ g_assert (!reader->joined);
+ reader->joined = joined;
+ reader->joined_data = data;
+ if (reader->pending)
+ g_cancellable_cancel (reader->cancel);
+ else
+ goodix_reader_joined (reader);
+}
+
+gboolean
+goodix_parse_reply (FpDevice *dev,
+ guint8 *out_category,
+ guint8 *out_command,
+ const guint8 **out_payload,
+ gsize *out_payload_len,
+ GError **error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (self->reply_valid)
+ {
+ *out_category = self->reply_category;
+ *out_command = self->reply_command;
+ *out_payload = self->reply_payload;
+ *out_payload_len = self->reply_payload_len;
+ return TRUE;
+ }
+
+ g_set_error_literal (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "Failed to parse device reply");
+ return FALSE;
+}
+
+gboolean
+goodix_parse_reply_exact (FpDevice *dev,
+ guint8 expected_category,
+ guint8 expected_command,
+ const guint8 **out_payload,
+ gsize *out_payload_len,
+ GError **error)
+{
+ guint8 category, command;
+
+ if (!goodix_parse_reply (dev, &category, &command, out_payload,
+ out_payload_len, error))
+ return FALSE;
+
+ if (category != expected_category || command != expected_command)
+ {
+ g_set_error (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "Unexpected reply: cat=0x%02x cmd=0x%02x",
+ category, command);
+ return FALSE;
+ }
+
+ return TRUE;
+}
diff --git a/libfprint/drivers/goodix53x5/device/transport.h b/libfprint/drivers/goodix53x5/device/transport.h
new file mode 100644
index 0000000..d44f938
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/device/transport.h
@@ -0,0 +1,141 @@
+/*
+ * Goodix 53x5 driver for libfprint — USB transport and command execution
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#pragma once
+
+#include "driver-private.h"
+
+/* Command bytes are copied when the request is accepted. */
+typedef struct _GoodixCmd
+{
+ guint8 category;
+ guint8 command;
+ guint8 *payload;
+ gsize payload_len;
+ gboolean use_checksum;
+} GoodixCmd;
+
+typedef struct
+{
+ GoodixCmd cmd;
+ /* A2 reset with data uses the shared A/0,A/1,A/4 event, ACK 500 ms,
+ * response 1000 ms, one attempt. Type-zero IRQ payload is {5,20}; its
+ * completed reply view contains the little-endian three-byte IRQ value.
+ * Without data the type-zero payload is {1,20}, ACK-only. */
+ gboolean expect_data;
+ /* Retained caller hint; IN now survives every command until quiesce. */
+ gboolean idle_after_ack;
+} GoodixTransportRequest;
+
+typedef struct
+{
+ /* Last accepted odd ACK; ordinary exhaustion follows native retry policy. */
+ guint8 ack_status;
+ gboolean ordinary_exhaustion;
+ gboolean write_cancelled;
+ gboolean restart_gtls;
+} GoodixTransportResult;
+
+/* One row of the native command table: the 53x5 ACK and data budgets, the
+ * response slot a reply lands in and whether the command is retried. */
+typedef struct
+{
+ guint8 command;
+ guint ack_ms;
+ guint response_ms;
+ GoodixResponseSlot response_slot;
+ gboolean retry;
+} GoodixCommandPolicy;
+
+/* Returns the native table's row for the command with wire byte @command,
+ * or NULL when the table does not list it. */
+const GoodixCommandPolicy *goodix_cmd_policy (guint8 command);
+
+/* Error ownership transfers to done. Result is borrowed for that call only.
+ * The completed operation is detached before caller code can submit another. */
+typedef void (*GoodixTransportDone) (FpDevice *dev,
+ const GoodixTransportResult *result,
+ GError *error, gpointer data);
+typedef void (*GoodixTransportJoined) (FpDevice *dev, gpointer data);
+
+/* Copy the request before returning. The independent IN remains posted. */
+void goodix_transport_command (FpDevice *dev, const GoodixTransportRequest *request,
+ GoodixTransportDone done, gpointer data);
+/* Writes a raw TLS record; completes once written, as no sensor ACKs one. */
+void goodix_transport_send_record (FpDevice *dev, GBytes *record,
+ GoodixTransportDone done, gpointer data);
+
+/* Entry points of the receiver for GoodixLink.receive: protocol messages
+ * go in as direct-framing cells, encrypted images and category-D data whole. */
+void goodix_rx_cell (GoodixTransport *operation, const guint8 *buffer,
+ gsize cell_length);
+gboolean goodix_rx_image (GoodixTransport *operation, const guint8 *payload,
+ gsize len);
+void goodix_mcu_publish (FpiDeviceGoodix53x5 *self, const guint8 *payload,
+ gsize len);
+void goodix_transport_wait_event (FpDevice *dev, GoodixProfile9FdtWaitMode mode,
+ GoodixTransportDone done, gpointer data);
+void goodix_transport_wait_mcu (FpDevice *dev, guint timeout, gsize length,
+ GoodixTransportDone done, gpointer data);
+void goodix_transport_reset_mcu (FpDevice *dev);
+void goodix_transport_cancel_event (FpDevice *dev);
+/* Foreground and CPU work must already be settled. Join the continuous IN;
+ * this is not a policy to cancel outstanding commands or CPU work. */
+void goodix_transport_quiesce (FpDevice *dev, GoodixTransportJoined joined,
+ gpointer data);
+
+/* Bytes per USB bulk packet; both framings pad writes to whole packets. */
+#define GOODIX_USB_CHUNK_SIZE 64
+
+/* Timeouts in ms */
+#define GOODIX_ACK_TIMEOUT 2000
+#define GOODIX_DATA_TIMEOUT 5000
+
+/* Commit the native parser-side base updates before publishing a notification.
+ * Dispatch must not apply these updates again for a selected notification. */
+void goodix_recv_apply_fdt_event (FpDevice *dev,
+ GoodixFdtEventType type,
+ const GoodixProfile9FdtEvent *event);
+
+/* Copy the validated notification selected by wait_event. Mode was used at
+ * decode time; selected type/event/predecessor are independent of later RX. */
+gboolean goodix_recv_select_fdt (FpDevice *dev, GoodixFdtEventType *type,
+ GoodixProfile9FdtEvent *event,
+ guint16 *prior_down, GError **error);
+
+/* Invalidate transport-local reception only after its owners have joined. */
+void goodix_transport_invalidate (FpDevice *dev);
+
+/* Access the transport's validated response view. Generic command completion
+ * selects the retained shared cache (and awaited selector), including data
+ * received before ACK. Other packets borrow RX storage. Consume either view
+ * before starting another receive; this does not reparse the wire bytes. */
+gboolean goodix_parse_reply (FpDevice *dev,
+ guint8 *out_category,
+ guint8 *out_command,
+ const guint8 **out_payload,
+ gsize *out_payload_len,
+ GError **error);
+
+gboolean goodix_parse_reply_exact (FpDevice *dev,
+ guint8 expected_category,
+ guint8 expected_command,
+ const guint8 **out_payload,
+ gsize *out_payload_len,
+ GError **error);
diff --git a/libfprint/drivers/goodix53x5/driver-private.h b/libfprint/drivers/goodix53x5/driver-private.h
new file mode 100644
index 0000000..04663dc
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/driver-private.h
@@ -0,0 +1,322 @@
+/*
+ * Goodix 53x5 driver for libfprint — Private device state
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#pragma once
+
+#include "fpi-device.h"
+#include "fpi-ssm.h"
+#include "fpi-usb-transfer.h"
+
+#include "goodix53x5.h"
+#include "device/proto.h"
+#include "device/crypto.h"
+#include "family.h"
+#include "device/debug.h"
+#include "device/base.h"
+#include "device/health.h"
+#include "milan/match/match.h"
+
+/* id_table driver_data selecting goodix_family_gm168sec. */
+#define GOODIX_FAMILY_GM168SEC 1
+
+/* USB interface claimed at open and released at close. */
+#define GOODIX_USB_INTERFACE(dev) \
+ (goodix_family (FPI_DEVICE_GOODIX53X5 (dev))->link.usb_interface)
+
+/* Sensor dimensions */
+#define GOODIX_SENSOR_WIDTH 108
+#define GOODIX_SENSOR_HEIGHT 88
+#define GOODIX_SENSOR_PIXELS (GOODIX_SENSOR_WIDTH * GOODIX_SENSOR_HEIGHT)
+#define GOODIX_SENSOR_RAW12_BYTES (((GOODIX_SENSOR_PIXELS + 3) / 4) * 6)
+
+/* Enroll stages */
+#define GOODIX_ENROLL_SAMPLES 12
+
+/* --- Calibration parameters (from OTP) --- */
+typedef struct
+{
+ guint16 tcode;
+ guint16 delta_fdt;
+ guint16 delta_down;
+ guint16 delta_up;
+ guint16 delta_img;
+ guint16 delta_nav;
+ guint16 dac_h;
+ guint16 dac_l;
+ guint16 dac_delta;
+ gboolean dac_from_otp;
+} GoodixCalibParams;
+
+/* Original OTP default and live adjustment history; current DAC is calib.dac_h. */
+typedef struct
+{
+ guint16 default_dac;
+ guint16 active;
+ guint16 adjustments;
+ guint16 high;
+ guint16 low;
+} GoodixDynamicDacState;
+
+typedef struct
+{
+ /* Receive identity and reverse predecessor travel with the coalesced slot;
+ * scan copies selected work before another packet can replace this slot. */
+ GoodixProfile9FdtEvent event;
+ GoodixFdtEventType type;
+} GoodixFdtNotification;
+
+typedef struct _GoodixTransport GoodixTransport;
+typedef struct _GoodixReader GoodixReader;
+typedef struct _GoodixTls GoodixTls;
+
+/* HAL +0x1e0: requested mode, independent of coordinator and FDT wait state. */
+typedef enum
+{
+ GOODIX_REQUESTED_MODE_CAPTURE = 0,
+ GOODIX_REQUESTED_MODE_SLEEP = 2,
+} GoodixRequestedMode;
+
+/* Independent native response events; the first four retain their existing
+ * readiness bits used by the named command consumers. */
+typedef enum
+{
+ GOODIX_RESPONSE_NONE = -1,
+ GOODIX_RESPONSE_MANUAL,
+ GOODIX_RESPONSE_CONFIG,
+ GOODIX_RESPONSE_SYSTEM,
+ GOODIX_RESPONSE_IMAGE,
+ GOODIX_RESPONSE_REGISTER,
+ GOODIX_RESPONSE_OTP,
+ GOODIX_RESPONSE_PRODUCTION,
+ GOODIX_RESPONSE_FIRMWARE,
+ GOODIX_RESPONSE_COUNT,
+} GoodixResponseSlot;
+
+/* --- Device struct --- */
+struct _FpiDeviceGoodix53x5
+{
+ FpDevice parent;
+
+ GCancellable *cancel;
+ /* Hardware service authority is independent of the current client action. */
+ GCancellable *session_cancel;
+ gboolean session_open;
+ /* Exactly one owner drives the hardware at a time: background maintenance
+ * (idle service or a detached deactivation tail), a foreground action, or
+ * the reader join requested by suspend/close. */
+ gboolean service_active;
+ gboolean foreground_active;
+ gboolean action_pending;
+ gboolean suspend_pending;
+ gboolean session_suspended;
+ /* Physical stop in flight; service_joined remains owned until its callback. */
+ gboolean service_draining;
+ void (*service_joined) (FpDevice *dev, gpointer data);
+ gpointer service_joined_data;
+
+ /* Owned by the GM168SEC link: its receive stream, reassembled into whole
+ * packs across transfers. */
+ GByteArray *pack_rx;
+ /* Owned by the GM168SEC channel: the TLS session images are decrypted
+ * through, replaced at every handshake. HTSEC sensors use gtls instead. */
+ GoodixTls *tls;
+
+ /* GTLS session (persists across captures) */
+ GoodixGtlsCtx gtls;
+ gboolean image_error_history;
+ gboolean gtls_restart_pending;
+ gboolean gtls_restart_active;
+
+ /* Calibration seeded from OTP; live reads update the current high DAC. */
+ GoodixCalibParams calib;
+ /* Per-device default and last live snapshot of module-owned DAC history. */
+ GoodixDynamicDacState dynamic_dac;
+ GoodixSensorHealth health;
+ /* Latest admitted hardware TX-on plane, independent of consumed setup.
+ * Owned until hardware teardown; recoverable base rejection retains it. */
+ guint16 *hardware_reference;
+ guint64 hardware_reference_id;
+ gboolean hardware_refresh_pending;
+ /* Installed hardware callback/count outlive an individual read attempt. */
+ guint capture_unread;
+ gboolean captured_enroll_allowed;
+ gboolean capture_callback_pending;
+
+ /* Reassembly buffer for multi-chunk reads */
+ GoodixReassembly rx;
+ /* Validated borrowed view, consumed before the next receive/invalidation. */
+ gboolean reply_valid;
+ guint8 reply_category;
+ guint8 reply_command;
+ const guint8 *reply_payload;
+ gsize reply_payload_len;
+ /* Category-D stream and coalesced receive signal survive ACK ownership.
+ * The selected view remains owned until the next receive or invalidation. */
+ GByteArray *mcu_rx;
+ GBytes *mcu_reply;
+ gboolean mcu_ready;
+ /* One handle-owned IN reader and a separately owned command/event waiter. */
+ GoodixReader *reader;
+ GoodixTransport *transport;
+
+ /* Native response events reset per send; cached bytes survive reset.
+ * The manual cache retains metadata for Linux touch-flag consumers. */
+ guint8 command_response_ready;
+ /* Configuration status of the last 9/2 reply. */
+ guint8 config_response_status;
+ /* The last download (9/0) reply's status byte, and whether the family's
+ * protocol reads it as a failure. */
+ guint8 config_download_status;
+ gboolean config_download_failed;
+ /* Receiver-owned decoded image, independent of the command ACK and of the
+ * captured frame handed to the runtime worker. Readiness resets per send. */
+ guint16 *image_response;
+ gboolean image_response_failed;
+ /* 533c only, from its CONFIG_LOST and RECONNECT events; 53x5 never sets
+ * the fields below up to psk_refresh_pending. */
+ /* Wrapped ACK loss state; a successful download clears it only after the
+ * independent loss notification has been serviced. */
+ gboolean config_lost;
+ gboolean config_restore_pending;
+ gboolean config_restore_active;
+ /* The selected reconnect arms down before any queued reconnect starts. */
+ gboolean reconnect_requested;
+ guint reconnect_pending;
+ /* Set by the 533c channel's config_lost hook; open/resume and reconnect
+ * check the PSK hash while it is set, failed-read recovery keeps it.
+ * Cleared only after a passed check, including across suspend. */
+ gboolean psk_refresh_pending;
+ guint8 manual_response[4 + GOODIX_FDT_BASE_LEN];
+ guint16 manual_touch;
+ /* Parser mutations precede coalesced notification. The latest reverse event
+ * retains the down base installed by its predecessor, not the arm payload. */
+ guint16 fdt_prior_down[GOODIX_PROFILE9_FDT_AREA_COUNT];
+ GoodixFdtNotification pending_fdt;
+ guint8 notice_irq[2];
+ gboolean rx_idle_partial;
+ GoodixRequestedMode requested_mode;
+
+ /* Profile-9 FDT state persists across actions and hardware reinitialization. */
+ GoodixProfile9FdtState profile9_fdt;
+
+ gboolean open_ref_powered;
+ gboolean open_usb_reset_required;
+ gboolean open_recovery_attempted;
+ gboolean open_gtls_failed;
+
+ /* OTP raw data */
+ guint8 *otp_data;
+ gsize otp_len;
+
+ /* Firmware version string */
+ gchar *fw_version;
+ /* Shared native cache, including retained unwritten suffixes. Keep the
+ * firmware consumer's 64-byte view while retaining complete framed replies. */
+ union
+ {
+ guint8 shared_response[64];
+ guint8 shared_response_storage[GOODIX_RX_BUF_SIZE];
+ };
+ /* Received lengths preserve Linux short-reply validation independently of
+ * the native event grouping and shared byte overwrites. */
+ gsize shared_response_lengths[GOODIX_RESPONSE_COUNT];
+
+ /* Hardware identity and its validated Milan algorithm subtype. */
+ guint32 chip_id;
+ guint16 milan_sensor_subtype;
+
+ /* Device-keyed identity for the persisted preprocessing subset. */
+ guint8 milan_persistence_identity[32];
+ gboolean milan_persistence_identity_valid;
+
+ /* One admitted TX-on setup generation per valid hardware session. */
+ GoodixMilanGeneration *milan_generation;
+ /* Algorithm state surviving close/reset, released with this device object. */
+ GoodixMilanGeneration *milan_retained_generation;
+ guint64 last_milan_generation_id;
+
+ /* Action-owned state to commit after post-scan hardware cleanup. */
+ GoodixMilanPreprocessState *pending_persistence_state;
+
+ /* TRUE while verifying a PSK write during open. */
+ gboolean psk_write_verify_pending;
+
+ /* GTLS PSK selected for this open. Imported keys are never provisioned by
+ * this driver because the arbitrary-key white-box encoder is not available. */
+ guint8 psk[GOODIX_PSK_LEN];
+ gboolean psk_imported;
+
+ /* USB interface state */
+ gboolean usb_interface_claimed;
+
+ /* A hardware fault requires cold reconstruction on resume or the next
+ * action. Ordinary sleep retains host state and only re-keys GTLS. */
+ gboolean needs_reinit;
+
+ /* Retained for the open/reinitialization parent SSM. */
+ FpiSsm *task_ssm;
+
+ /* Result computed by the CPU worker, delivered when the action completes. */
+ gboolean pending_result_report;
+ FpiDeviceAction pending_result_action;
+ FpiMatchResult pending_verify_result;
+ FpPrint *pending_identify_match;
+ FpPrint *pending_update_target;
+ GVariant *pending_update_data;
+ GError *pending_result_error;
+ GError *pending_learning_error;
+
+ /* Native CPU work is isolated in one cancellable task. Only its callback on
+ * the action's main context may commit generation state or publish results. */
+ GTask *milan_task;
+ guint64 action_epoch;
+
+#ifdef GOODIX53X5_DEBUG
+ guint8 *captured_image; /* native profile-9 diagnostic presentation */
+#endif
+
+ /* Canonical raw 12-bit live frame. Production owns this independently of
+ * debug dumping until the current auth/enroll action consumes or clears it. */
+ guint16 *captured_raw_image;
+
+#ifdef GOODIX53X5_DEBUG
+ GoodixDebugTiming debug_timing;
+ gchar debug_capture_session_id[37];
+ guint64 debug_chronology;
+#endif
+
+ /* Enrollment tracking */
+ GoodixMilanEnrollmentTransaction *enroll_transaction;
+ gint enroll_stage;
+ guint enroll_bad_record_count;
+ guint enroll_bad_continue_count;
+ gboolean pending_enroll_progress;
+ gint pending_enroll_stage;
+ GError *pending_enroll_error;
+};
+
+/* Returns the sensor's family. Wild OS builds only the 533c (GM168SEC)
+ * family: the HTSEC family provisions a PSK on 5335/5385/5395 sensors, and
+ * no code that writes a key to a sensor is built. */
+static inline const GoodixFamily *
+goodix_family (FpiDeviceGoodix53x5 *self)
+{
+ (void) self;
+ return &goodix_family_gm168sec;
+}
diff --git a/libfprint/drivers/goodix53x5/family.h b/libfprint/drivers/goodix53x5/family.h
new file mode 100644
index 0000000..c7f9b2b
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/family.h
@@ -0,0 +1,185 @@
+/*
+ * Goodix 53x5 driver for libfprint — sensor families
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include <glib.h>
+
+typedef struct _FpDevice FpDevice;
+typedef struct _FpiSsm FpiSsm;
+typedef struct _FpiDeviceGoodix53x5 FpiDeviceGoodix53x5;
+typedef struct _GoodixTransport GoodixTransport;
+typedef struct _GoodixCmd GoodixCmd;
+
+/* How the bytes of one sensor family reach the driver. */
+typedef struct
+{
+ guint8 usb_interface;
+ guint8 ep_in;
+ guint8 ep_out;
+ /* Returns the bytes to write for the protocol message @msg, or NULL when
+ * the framing cannot carry it. */
+ guint8 *(*frame) (const guint8 *msg, gsize msg_len, gsize *out_len);
+ /* Returns the bytes to write for a raw secure-channel record, or NULL when
+ * the framing cannot carry it; NULL where the channel rides in protocol
+ * messages and nothing is written raw. */
+ guint8 *(*frame_record) (GBytes *record, gsize *out_len);
+ /* Hands the bytes of one completed IN transfer to the receiver through
+ * goodix_rx_cell(), goodix_rx_image() and goodix_mcu_publish(). */
+ void (*receive) (FpiDeviceGoodix53x5 *self, GoodixTransport *operation,
+ const guint8 *data, gsize len);
+ /* Drops any partial frame kept between transfers; NULL where none is. */
+ void (*discard) (FpiDeviceGoodix53x5 *self);
+} GoodixLink;
+
+/* What a message from the sensor means beyond being a reply. */
+typedef enum
+{
+ GOODIX_SENSOR_EVENT_NONE,
+ /* The sensor lost its configuration and keys; the scan restores the
+ * configuration and the next channel handshake re-checks the PSK. */
+ GOODIX_SENSOR_EVENT_CONFIG_LOST,
+ /* The sensor asks for a new secure-channel session, after which finger
+ * detection is armed again. */
+ GOODIX_SENSOR_EVENT_RECONNECT,
+} GoodixSensorEvent;
+
+typedef enum
+{
+ GOODIX_FDT_EVENT_DOWN = 0,
+ GOODIX_FDT_EVENT_UP,
+ GOODIX_FDT_EVENT_REVERSE,
+ GOODIX_FDT_EVENT_NONE,
+ GOODIX_FDT_EVENT_CONFIG,
+ GOODIX_FDT_EVENT_ESD,
+ GOODIX_FDT_EVENT_WAKE,
+ GOODIX_FDT_EVENT_DEACTIVATE,
+} GoodixFdtEventType;
+
+#define GOODIX_FDT_IRQ_DOWN 0x0002
+#define GOODIX_FDT_IRQ_REVERSE 0x0080
+#define GOODIX_FDT_IRQ_REVERSE_ALT 0x0082
+#define GOODIX_FDT_IRQ_UP 0x0200
+
+/* The family's rules of the shared MCU protocol. */
+typedef struct
+{
+ /* Bytes of the wake NOP's zero payload. */
+ gsize wake_payload_len;
+ /* The EC-control payload that isolates the power button while the sensor
+ * scans; every family ends isolation with three zero bytes. */
+ guint8 ec_on_payload[3];
+ /* Sets the ACK and data budgets, in ms, and permits one timeout retry. */
+ gboolean (*command_budget) (guint8 command, gboolean expect_data,
+ guint *ack_ms, guint *response_ms);
+ /* Checks whether a failed write may use the command's retry. */
+ gboolean (*retry_write) (const GError *error);
+ /* Checks whether an arm ACK needs a local config download and repeat. */
+ gboolean (*repair_arm) (guint8 status);
+ /* Selects up rather than down after a wake notice. */
+ gboolean (*wake_arm_up) (gboolean waiting_up);
+ /* Publishes a valid ESD notice's IRQ in the family's response storage. */
+ gboolean (*notice_irq) (FpiDeviceGoodix53x5 *self, const guint8 *payload, gsize len);
+ /* Validates and classifies a down/up notification. */
+ GoodixFdtEventType (*fdt_event) (FpiDeviceGoodix53x5 *self,
+ const guint8 *payload, gsize len, GError **error);
+ /* TRUE where an ACK that does not come in time is not an error for a
+ * command that expects data: the wait moves on to the data, as the
+ * vendor's _IoHubExec does. FALSE retries the command. */
+ gboolean ack_timeout_waits_for_data;
+ /* Returns the event a complete, valid message carries, or NONE. */
+ GoodixSensorEvent (*event) (guint8 category, guint8 command,
+ const guint8 *payload, gsize len);
+ /* Checks whether a reply with @category/@command answers @awaited when
+ * both share a response slot. */
+ gboolean (*reply_answers) (guint8 category, guint8 command,
+ const GoodixCmd *awaited);
+ /* Checks whether a configuration download reply reports success. */
+ gboolean (*download_succeeded) (const guint8 *payload, gsize len);
+ /* Checks whether the driver may send @cmd at all. */
+ gboolean (*may_send) (const GoodixCmd *cmd);
+} GoodixProtocol;
+
+typedef enum
+{
+ /* Decrypted by the established session. */
+ GOODIX_FRAME_DECRYPTED,
+ /* Rejected before the session was established; says nothing about the session. */
+ GOODIX_FRAME_REJECTED,
+ /* Rejected on an established session; counts towards restarting it. */
+ GOODIX_FRAME_REJECTED_IN_SESSION,
+ /* Decrypted, but not an image; the session that decrypted it is sound. */
+ GOODIX_FRAME_INVALID,
+} GoodixFrameStatus;
+
+/* Handshake attempts before a secure-channel start gives up, by what
+ * started it. */
+typedef struct
+{
+ /* Open and resume. */
+ guint open;
+ /* A restart after an image read the channel rejected. */
+ guint after_failed_read;
+ /* A new session the sensor asked for. */
+ guint reconnect;
+} GoodixChannelAttempts;
+
+/* The family's secure channel. */
+typedef enum
+{
+ GOODIX_CHANNEL_START,
+ GOODIX_CHANNEL_FAILED_READ,
+ GOODIX_CHANNEL_RECONNECT,
+} GoodixChannelReason;
+
+typedef struct
+{
+ /* The channel's name in logs. */
+ const char *name;
+ GoodixChannelAttempts attempts;
+ guint retry_delay_ms;
+ /* Returns a new SSM for one handshake attempt. */
+ FpiSsm *(*attempt_new) (FpDevice *dev, GoodixChannelReason reason);
+ /* Decrypts an encrypted image payload into raw12 bytes in @out. */
+ GoodixFrameStatus (*decrypt_frame) (FpiDeviceGoodix53x5 *self,
+ const guint8 *payload, gsize len,
+ guint8 **out, gsize *out_len);
+ /* Counts one undecodable frame; returns TRUE when the channel must be
+ * restarted for it. */
+ gboolean (*image_error) (FpiDeviceGoodix53x5 *self);
+ /* Checks whether a failed capture may arm while channel recovery is pending. */
+ gboolean (*rearm_after_capture) (FpiDeviceGoodix53x5 *self);
+ /* TRUE where starting a new session drops the finger-detect arm, so a
+ * restart still pending runs before an arm. */
+ gboolean restart_disarms;
+ /* Notes an ACK reporting lost configuration, before the shared loss state
+ * changes; NULL where the channel keeps no state for it. */
+ void (*config_lost) (FpiDeviceGoodix53x5 *self);
+ /* Forgets the session and its keys when the device closes; NULL where
+ * the channel keeps nothing beyond the shared PSK. */
+ void (*discard) (FpiDeviceGoodix53x5 *self);
+} GoodixChannel;
+
+/* One sensor family: the same GF5288 sensor and pipeline behind its own MCU
+ * firmware. Shared code uses these pieces and never asks which family it
+ * runs. */
+typedef struct
+{
+ GoodixLink link;
+ GoodixProtocol protocol;
+ GoodixChannel channel;
+ /* Returns a new SSM running the family's bring-up, from the first probe
+ * to the established secure channel. The open SSM runs it between claiming
+ * the interface and the first configuration download. */
+ FpiSsm *(*open_new) (FpDevice *dev);
+} GoodixFamily;
+
+/* 533c: wrapped framing on interface 0, TLS 1.2-PSK, GM168SEC MCU. */
+extern const GoodixFamily goodix_family_gm168sec;
diff --git a/libfprint/drivers/goodix53x5/family/gm168sec/channel.c b/libfprint/drivers/goodix53x5/family/gm168sec/channel.c
new file mode 100644
index 0000000..53f047d
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/family/gm168sec/channel.c
@@ -0,0 +1,229 @@
+/*
+ * Goodix 53x5 driver for libfprint — the GM168SEC secure channel (TLS 1.2-PSK)
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/transport.h"
+#include "device/commands.h"
+#include "device/session.h"
+#include "device/crypto.h"
+#include "family/gm168sec/gm168sec.h"
+#include "family/gm168sec/tls.h"
+
+/* FpParseImage takes exactly the raw12 pixels and their CRC. */
+#define GOODIX_WRAPPED_IMAGE_LEN (GOODIX_SENSOR_RAW12_BYTES + 4)
+
+/* Checks whether @image is a whole raw12 image whose trailing CRC, in the
+ * sensor's byte order, matches its pixels. */
+static gboolean
+goodix_wrapped_image_valid (const guint8 *image, gsize len)
+{
+ return len == GOODIX_WRAPPED_IMAGE_LEN &&
+ goodix_crypto_crc32_mpeg2 (image, GOODIX_SENSOR_RAW12_BYTES) ==
+ goodix_crypto_decode_u32 (image + GOODIX_SENSOR_RAW12_BYTES);
+}
+
+GoodixFrameStatus
+goodix_decrypt_frame_tls (FpiDeviceGoodix53x5 *self, const guint8 *payload,
+ gsize len, guint8 **out, gsize *out_len)
+{
+ gboolean established = self->tls && goodix_tls_established (self->tls);
+
+ *out = established ? goodix_tls_decrypt (self->tls, payload, len, out_len) : NULL;
+ if (*out && !goodix_wrapped_image_valid (*out, *out_len))
+ {
+ /* The vendor restarts TLS only when the read itself fails. */
+ fp_warn ("Rejecting a %zu-byte image without a valid CRC", *out_len);
+ g_clear_pointer (out, g_free);
+ return GOODIX_FRAME_INVALID;
+ }
+ if (*out)
+ return GOODIX_FRAME_DECRYPTED;
+ return established ? GOODIX_FRAME_REJECTED_IN_SESSION : GOODIX_FRAME_REJECTED;
+}
+
+/* OpenSSL returns a flight; the sensor receives one pack per TLS record. */
+static void
+goodix_tls_send_handler (FpiSsm *ssm, FpDevice *dev)
+{
+ GBytes *out = fpi_ssm_get_data (ssm);
+ gsize len;
+ const guint8 *data = g_bytes_get_data (out, &len);
+ g_autoptr(GError) error = NULL;
+
+ if (g_cancellable_set_error_if_cancelled (goodix_session_io_cancellable (dev), &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+
+ if (fpi_ssm_get_cur_state (ssm) == 1)
+ /* TOD's write and send callback sleep 1 + 2 ms, even on the last record. */
+ fpi_ssm_jump_to_state_delayed (ssm, 0, 3);
+ else if (!len)
+ fpi_ssm_mark_completed (ssm);
+ else
+ {
+ gsize record_len = GOODIX_TLS_RECORD_HEADER + (data[3] << 8 | data[4]);
+ g_autoptr(GBytes) record = g_bytes_new_from_bytes (out, 0, record_len);
+ GBytes *remaining = g_bytes_new_from_bytes (out, record_len, len - record_len);
+
+ fpi_ssm_set_data (ssm, remaining, (GDestroyNotify) g_bytes_unref);
+ goodix_cmd_send_tls_record (ssm, dev, record);
+ }
+}
+
+typedef enum {
+ GOODIX_TLS_PSK_REFRESH,
+ GOODIX_TLS_PSK_CHECK,
+ GOODIX_TLS_REQUEST,
+ GOODIX_TLS_RECV,
+ GOODIX_TLS_STEP,
+ GOODIX_TLS_SENT,
+ GOODIX_TLS_NUM_STATES,
+} GoodixTlsState;
+
+static void
+goodix_tls_received (FpDevice *dev, const GoodixTransportResult *result,
+ GError *error, gpointer data)
+{
+ FpiSsm *ssm = data;
+
+ if (g_error_matches (error, G_USB_DEVICE_ERROR, G_USB_DEVICE_ERROR_TIMED_OUT))
+ g_clear_error (&error);
+ if (error)
+ fpi_ssm_mark_failed (ssm, error);
+ else
+ fpi_ssm_next_state (ssm);
+}
+
+/* Runs one TLS handshake attempt, the sensor being the client, reading the
+ * PSK hash first when the sensor reported a power loss. Fails when the hash is
+ * not this driver's, the sensor sends a record OpenSSL rejects, or the
+ * handshake runs out of steps. */
+static void
+goodix_tls_ssm_handler (FpiSsm *ssm, FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ g_autoptr(GError) error = NULL;
+
+ if (g_cancellable_set_error_if_cancelled (goodix_session_io_cancellable (dev), &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+
+ switch ((GoodixTlsState) fpi_ssm_get_cur_state (ssm))
+ {
+ case GOODIX_TLS_PSK_REFRESH:
+ if (!self->psk_refresh_pending)
+ fpi_ssm_jump_to_state (ssm, GOODIX_TLS_REQUEST);
+ else
+ goodix_cmd_preset_read (ssm, dev, GOODIX_WRAPPED_PSK_HASH_TYPE, GOODIX_PSK_HASH_LEN);
+ break;
+
+ case GOODIX_TLS_PSK_CHECK:
+ if (!goodix_require_current_psk (dev, GOODIX_WRAPPED_PSK_HASH_TYPE, &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ self->psk_refresh_pending = FALSE;
+ fpi_ssm_next_state (ssm);
+ break;
+
+ case GOODIX_TLS_REQUEST:
+ goodix_transport_reset_mcu (dev);
+ self->mcu_ready = FALSE;
+ g_clear_pointer (&self->tls, goodix_tls_free);
+ self->tls = goodix_tls_new (self->psk, GOODIX_PSK_LEN, &error);
+ if (!self->tls)
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ goodix_cmd_tls_request (ssm, dev);
+ break;
+
+ case GOODIX_TLS_RECV:
+ goodix_transport_wait_mcu (dev, 50, 0, goodix_tls_received, ssm);
+ break;
+
+ case GOODIX_TLS_STEP:
+ {
+ g_autoptr(GBytes) out = NULL;
+ const guint8 *in = NULL;
+ gsize in_len = 0;
+
+ if (self->mcu_reply)
+ in = g_bytes_get_data (self->mcu_reply, &in_len);
+ if (!goodix_tls_handshake (self->tls, in, in_len, &out, &error))
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ else if (out)
+ {
+ FpiSsm *send = fpi_ssm_new (dev, goodix_tls_send_handler, 2);
+
+ fpi_ssm_set_data (send, g_steal_pointer (&out), (GDestroyNotify) g_bytes_unref);
+ fpi_ssm_start_subsm (ssm, send);
+ }
+ else
+ fpi_ssm_next_state (ssm);
+ }
+ break;
+
+ case GOODIX_TLS_SENT:
+ /* The Geneva handshake sends nothing after the last record. */
+ if (goodix_tls_established (self->tls))
+ fpi_ssm_mark_completed (ssm);
+ else if (!goodix_tls_handshake_pending (self->tls))
+ fpi_ssm_mark_failed (ssm, fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_PROTO, "TLS handshake did not finish in ten empty waits"));
+ else
+ fpi_ssm_jump_to_state (ssm, GOODIX_TLS_RECV);
+ break;
+
+ case GOODIX_TLS_NUM_STATES:
+ g_assert_not_reached ();
+ }
+}
+
+static void
+goodix_tls_read_restart_handler (FpiSsm *ssm, FpDevice *dev)
+{
+ if (fpi_ssm_get_cur_state (ssm) == GOODIX_TLS_PSK_REFRESH)
+ fpi_ssm_jump_to_state (ssm, GOODIX_TLS_REQUEST);
+ else
+ goodix_tls_ssm_handler (ssm, dev);
+}
+
+FpiSsm *
+goodix_tls_attempt_new (FpDevice *dev, GoodixChannelReason reason)
+{
+ return fpi_ssm_new (dev, reason == GOODIX_CHANNEL_FAILED_READ ?
+ goodix_tls_read_restart_handler : goodix_tls_ssm_handler,
+ GOODIX_TLS_NUM_STATES);
+}
+
+/* An OpenSSL session is dead after a failed record, so every undecodable
+ * frame restarts it. */
+gboolean
+goodix_tls_image_error (FpiDeviceGoodix53x5 *self)
+{
+ (void) self;
+ return TRUE;
+}
+
+void
+goodix_tls_discard (FpiDeviceGoodix53x5 *self)
+{
+ g_clear_pointer (&self->tls, goodix_tls_free);
+}
diff --git a/libfprint/drivers/goodix53x5/family/gm168sec/gm168sec.c b/libfprint/drivers/goodix53x5/family/gm168sec/gm168sec.c
new file mode 100644
index 0000000..d9805ad
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/family/gm168sec/gm168sec.c
@@ -0,0 +1,497 @@
+/*
+ * Goodix 53x5 driver for libfprint — the GM168SEC family (27c6:533c)
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+/* 533c is the GF5288 of the 53x5 parts behind a GM168SEC secure element: the
+ * same commands and image pipeline, carried in the wrapped framing of the 51x7
+ * family and secured with standard TLS 1.2-PSK, the sensor being the client. */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/transport.h"
+#include "family/gm168sec/gm168sec.h"
+#include "family/gm168sec/tls.h"
+
+#include <string.h>
+
+/* Wrapped framing: [flags(1)][length(2 LE)][sum of the first three(1)]
+ * then length bytes. The high nibble of the flags is the family: 0xa packs
+ * carry one protocol message, 0xb packs TLS records, behind a 9-byte prefix
+ * when flag 0x02 is set (0xb2, image data). */
+#define GOODIX_PACK_HEADER 4
+#define GOODIX_PACK_MESSAGE 0xa0
+#define GOODIX_PACK_TLS 0xb0
+#define GOODIX_PACK_FAMILY_MESSAGE 0xa
+#define GOODIX_PACK_FAMILY_TLS 0xb
+#define GOODIX_PACK_TLS_PREFIXED 0x02
+/* The largest TLS record RFC 5246 allows (2^14 + 2048 bytes and its 5-byte
+ * header) behind the prefix; a longer pack is a misread header. */
+#define GOODIX_PACK_MAX_PAYLOAD (GOODIX_PACK_TLS_DATA_HDR + GOODIX_TLS_RECORD_HEADER + \
+ 16384 + 2048)
+
+/* Returns the checksum a pack header carries in its fourth byte. */
+static guint8
+goodix_pack_checksum (const guint8 *header)
+{
+ return header[0] + header[1] + header[2];
+}
+
+static void
+goodix_pack_write_header (guint8 *header, guint8 flags, gsize len)
+{
+ header[0] = flags;
+ header[1] = len & 0xff;
+ header[2] = (len >> 8) & 0xff;
+ header[3] = goodix_pack_checksum (header);
+}
+
+/* Returns the payload length a pack header announces, or FALSE when it is
+ * not a header: an unknown family, a wrong checksum or an impossible length. */
+static gboolean
+goodix_pack_read_header (const guint8 *header, gsize *len)
+{
+ guint8 family = header[0] >> 4;
+
+ if ((family != GOODIX_PACK_FAMILY_MESSAGE && family != GOODIX_PACK_FAMILY_TLS) ||
+ goodix_pack_checksum (header) != header[3])
+ return FALSE;
+ *len = header[1] | (header[2] << 8);
+ return *len <= GOODIX_PACK_MAX_PAYLOAD;
+}
+
+/* Returns @data as one pack of kind @flags, zero-padded to whole 64-byte
+ * writes, or NULL when @data does not fit the header's 16-bit length. */
+static guint8 *
+goodix_frame_pack (guint8 flags, const guint8 *data, gsize data_len, gsize *out_len)
+{
+ gsize len = (GOODIX_PACK_HEADER + data_len + GOODIX_USB_CHUNK_SIZE - 1) /
+ GOODIX_USB_CHUNK_SIZE * GOODIX_USB_CHUNK_SIZE;
+ guint8 *framed;
+
+ if (data_len > G_MAXUINT16)
+ return NULL;
+ framed = g_malloc0 (len);
+ goodix_pack_write_header (framed, flags, data_len);
+ memcpy (framed + GOODIX_PACK_HEADER, data, data_len);
+ *out_len = len;
+ return framed;
+}
+
+static guint8 *
+goodix_frame_wrapped (const guint8 *msg, gsize msg_len, gsize *out_len)
+{
+ return goodix_frame_pack (GOODIX_PACK_MESSAGE, msg, msg_len, out_len);
+}
+
+static guint8 *
+goodix_frame_tls_record (GBytes *record, gsize *out_len)
+{
+ gsize len;
+ const guint8 *data = g_bytes_get_data (record, &len);
+
+ return goodix_frame_pack (GOODIX_PACK_TLS, data, len, out_len);
+}
+
+/* Passes one protocol message to the receiver as the 64-byte direct-framing
+ * cells it would have arrived in, so both framings share one parser. */
+static void
+goodix_rx_message (GoodixTransport *operation, const guint8 *msg, gsize len)
+{
+ guint8 cell[GOODIX_USB_CHUNK_SIZE];
+ gsize offset = MIN (len, GOODIX_USB_CHUNK_SIZE);
+
+ goodix_rx_cell (operation, msg, offset);
+ while (offset < len)
+ {
+ gsize n = MIN (len - offset, GOODIX_USB_CHUNK_SIZE - 1);
+
+ cell[0] = msg[0] | 1;
+ memcpy (cell + 1, msg + offset, n);
+ goodix_rx_cell (operation, cell, n + 1);
+ offset += n;
+ }
+}
+
+static void
+goodix_rx_pack (FpiDeviceGoodix53x5 *self, GoodixTransport *operation,
+ guint8 flags, const guint8 *payload, gsize len)
+{
+ if (flags >> 4 == GOODIX_PACK_FAMILY_MESSAGE)
+ {
+ if (len)
+ goodix_rx_message (operation, payload, len);
+ }
+ else
+ {
+ if (flags & GOODIX_PACK_TLS_PREFIXED)
+ {
+ if (len < GOODIX_PACK_TLS_DATA_HDR)
+ return;
+ payload += GOODIX_PACK_TLS_DATA_HDR;
+ len -= GOODIX_PACK_TLS_DATA_HDR;
+ }
+ if (self->tls && goodix_tls_established (self->tls))
+ goodix_rx_image (operation, payload, len);
+ else
+ /* Handshake records share the category-D stream and its waiter. */
+ goodix_mcu_publish (self, payload, len);
+ }
+}
+
+/* Drops the partial pack kept for the next transfer, if any. */
+void
+goodix_drop_pack_stream (FpiDeviceGoodix53x5 *self)
+{
+ g_clear_pointer (&self->pack_rx, g_byte_array_unref);
+}
+
+/* Dispatches every complete pack once @data is appended to the stream,
+ * keeping a partial one for the next transfer; drops the stream at a bad
+ * header. A pack never starts with zero, so its write padding is skipped. */
+static void
+goodix_receive_wrapped (FpiDeviceGoodix53x5 *self, GoodixTransport *operation,
+ const guint8 *data, gsize len)
+{
+ GByteArray *stream;
+
+ if (!self->pack_rx)
+ self->pack_rx = g_byte_array_new ();
+ stream = self->pack_rx;
+ g_byte_array_append (stream, data, len);
+
+ for (;;)
+ {
+ gsize padding = 0, length;
+
+ while (padding < stream->len && !stream->data[padding])
+ padding++;
+ g_byte_array_remove_range (stream, 0, padding);
+ if (stream->len < GOODIX_PACK_HEADER)
+ return;
+ if (!goodix_pack_read_header (stream->data, &length))
+ {
+ fp_warn ("Dropping %u wrapped bytes with a bad pack header", stream->len);
+ g_byte_array_set_size (stream, 0);
+ return;
+ }
+ if (stream->len < GOODIX_PACK_HEADER + length)
+ return;
+ goodix_rx_pack (self, operation, stream->data[0],
+ stream->data + GOODIX_PACK_HEADER, length);
+ g_byte_array_remove_range (stream, 0, GOODIX_PACK_HEADER + length);
+ }
+}
+
+/* Checks whether @firmware parses as chip_platform_mode_version, such as
+ * GF5288_GM168SEC_APP_13016, and names the GM168 or GM168SEC platform, as
+ * the vendor's SelfCheck requires. */
+static gboolean
+goodix_wrapped_self_check (const char *firmware)
+{
+ g_auto(GStrv) fields = g_strsplit (firmware, "_", 4);
+ const char *platform;
+
+ if (g_strv_length (fields) != 4)
+ return FALSE;
+ platform = fields[1];
+ return g_ascii_strcasecmp (platform, "GM168") == 0 ||
+ g_ascii_strcasecmp (platform, "GM168SEC") == 0;
+}
+
+GError *
+goodix_gm168sec_check_firmware (const char *firmware)
+{
+ if (!firmware)
+ return fpi_device_error_new_msg (FP_DEVICE_ERROR_PROTO, "Firmware version unreadable");
+ fp_info ("Sensor firmware: %s", firmware);
+ /* Dell's Windows driver leaves the sensor in its bootloader (IAP) after it
+ * sets its own key, until Windows restarts. Nothing here may touch it. */
+ if (strstr (firmware, "_IAP_"))
+ return fpi_device_error_new_msg (FP_DEVICE_ERROR_NOT_SUPPORTED,
+ "Sensor is in its bootloader (firmware %s): "
+ "Windows Hello has not finished setting it up",
+ firmware);
+ if (!goodix_wrapped_self_check (firmware))
+ return fpi_device_error_new_msg (FP_DEVICE_ERROR_NOT_SUPPORTED,
+ "Firmware %s is not for this sensor's MCU", firmware);
+ return NULL;
+}
+
+/* The vendor's MCU context waits 1500 ms for every ACK and every reply;
+ * EC control alone gives its ACK 500 ms. Dell's TOD driver never enables
+ * the IoHub retry for this MCU, so every command goes out once; the Windows
+ * driver would resend once after a timeout. */
+static gboolean
+goodix_wrapped_command_budget (guint8 command, gboolean expect_data,
+ guint *ack_ms, guint *response_ms)
+{
+ (void) expect_data;
+ *ack_ms = command == 0xae ? 500 : 1500;
+ *response_ms = 1500;
+ return FALSE;
+}
+
+static gboolean
+goodix_gm168sec_retry_write (const GError *error)
+{
+ (void) error;
+ return FALSE;
+}
+
+/* ACK flag 0x02, on any command, means the sensor lost its configuration
+ * and needs it downloaded again. */
+#define GOODIX_PROTO_ACK_FLAG_CONFIG_LOST 0x02
+
+static gboolean
+goodix_gm168sec_repair_arm (guint8 status)
+{
+ (void) status;
+ return FALSE;
+}
+
+/* An ACK flagging lost configuration reports that loss; a D0 message asks
+ * for a new secure-channel session rather than carrying channel bytes. */
+static GoodixSensorEvent
+goodix_gm168sec_event (guint8 category, guint8 command, const guint8 *payload, gsize len)
+{
+ if (category == GOODIX_PROTO_CATEGORY_ACK && command == GOODIX_PROTO_CMD_ACK &&
+ len >= 2 && (payload[1] & GOODIX_PROTO_ACK_FLAG_CONFIG_LOST))
+ return GOODIX_SENSOR_EVENT_CONFIG_LOST;
+ if (category == GOODIX_PROTO_CATEGORY_MCU && command == 0)
+ return GOODIX_SENSOR_EVENT_RECONNECT;
+ return GOODIX_SENSOR_EVENT_NONE;
+}
+
+static gboolean
+goodix_gm168sec_wake_arm_up (gboolean waiting_up)
+{
+ (void) waiting_up;
+ return FALSE;
+}
+
+/* A reply answers a command only if its category and command are that
+ * command's, as the vendor's IoHubNotifyDataIn checks. */
+static gboolean
+goodix_gm168sec_reply_answers (guint8 category, guint8 command, const GoodixCmd *awaited)
+{
+ return category == awaited->category && command == awaited->command;
+}
+
+/* The download reply's first byte is 1 on success. */
+static gboolean
+goodix_gm168sec_download_succeeded (const guint8 *payload, gsize len)
+{
+ return len && payload[0] == 1;
+}
+
+/* Checks whether @cmd is a preset-slot read: e4 with a length, a zero
+ * offset, a slot and a zero word. A PSK write may also use e4, but its
+ * payload is a fragment header and data, never this. */
+static gboolean
+goodix_cmd_is_preset_read (const GoodixCmd *cmd)
+{
+ static const guint8 zero[4] = { 0 };
+
+ return cmd->category == GOODIX_PROTO_CATEGORY_PRODUCTION && cmd->command == 0x2 &&
+ cmd->payload_len == 16 && memcmp (cmd->payload + 4, zero, 4) == 0 &&
+ memcmp (cmd->payload + 12, zero, 4) == 0;
+}
+
+/* Checks whether @cmd could change what the sensor stores: any production
+ * command but a preset read (e0 and e2 writes, e4 used as a write), a
+ * firmware write (f0) or an APP erase (a4). */
+static gboolean
+goodix_cmd_writes_sensor (const GoodixCmd *cmd)
+{
+ if (cmd->category == GOODIX_PROTO_CATEGORY_PRODUCTION)
+ return !goodix_cmd_is_preset_read (cmd);
+ return (cmd->category == GOODIX_PROTO_CATEGORY_FIRMWARE && cmd->command == 0x0) ||
+ (cmd->category == GOODIX_PROTO_CATEGORY_SYSTEM && cmd->command == 0x2);
+}
+
+/* 533c returns no firmware in APP mode, so nothing could restore it: the
+ * driver never writes to the sensor.
+ *
+ * Wild OS sends only the commands this driver's 533c path is known to use,
+ * so a command outside the list fails before it reaches the USB endpoint,
+ * whatever it is. None of them changes what the sensor stores: the
+ * configuration download (9/0) and finger-detect arms live in the MCU's RAM
+ * and are sent again after every reset or power loss. */
+static gboolean
+goodix_gm168sec_may_send (const GoodixCmd *cmd)
+{
+ if (goodix_cmd_writes_sensor (cmd))
+ return FALSE;
+
+ switch (cmd->category)
+ {
+ case GOODIX_PROTO_CATEGORY_NOP:
+ /* Wake. */
+ return cmd->command == 0;
+
+ case GOODIX_PROTO_CATEGORY_IMAGE:
+ /* Image request. */
+ return cmd->command == 0;
+
+ case GOODIX_PROTO_CATEGORY_FDT:
+ /* Finger-down, finger-up and manual finger detection. */
+ return cmd->command == GOODIX_PROTO_CMD_FDT_DOWN ||
+ cmd->command == GOODIX_PROTO_CMD_FDT_UP ||
+ cmd->command == GOODIX_PROTO_CMD_FDT_MANUAL;
+
+ case 0x6:
+ /* Sleep mode. */
+ return cmd->command == 0;
+
+ case GOODIX_PROTO_CATEGORY_REGISTER:
+ /* Register read (the chip ID). */
+ return cmd->command == 1;
+
+ case GOODIX_PROTO_CATEGORY_CONFIG:
+ /* Configuration download into the MCU's RAM. */
+ return cmd->command == GOODIX_PROTO_CMD_CONFIG_DOWNLOAD;
+
+ case GOODIX_PROTO_CATEGORY_SYSTEM:
+ /* MCU reset, OTP read, firmware version read, power button isolation. */
+ return cmd->command == 1 || cmd->command == 3 || cmd->command == 4 ||
+ cmd->command == 7;
+
+ case GOODIX_PROTO_CATEGORY_MCU:
+ /* Asks the sensor to start its TLS handshake. */
+ return cmd->command == 0;
+
+ case GOODIX_PROTO_CATEGORY_PRODUCTION:
+ /* The PSK hash read from its preset slot. */
+ return goodix_cmd_is_preset_read (cmd);
+
+ default:
+ return FALSE;
+ }
+}
+
+static gboolean
+goodix_gm168sec_rearm_after_capture (FpiDeviceGoodix53x5 *self)
+{
+ return !self->psk_refresh_pending;
+}
+
+/* Every ACK reports the loss until a restore; only the first is a new power
+ * loss, after which the next handshake checks the PSK. Dell's drivers set
+ * the flag on every such ACK. Keeping the first-loss rule stops later ACKs
+ * setting it again after the check, which would leave a failed capture
+ * unarmed. */
+static void
+goodix_gm168sec_config_lost (FpiDeviceGoodix53x5 *self)
+{
+ if (!self->config_lost)
+ self->psk_refresh_pending = TRUE;
+}
+
+static gboolean
+goodix_gm168sec_notice_irq (FpiDeviceGoodix53x5 *self, const guint8 *payload, gsize len)
+{
+ if (len < sizeof (self->notice_irq))
+ return FALSE;
+ memcpy (self->notice_irq, payload, sizeof (self->notice_irq));
+ return TRUE;
+}
+
+static GoodixFdtEventType
+goodix_gm168sec_fdt_event (FpiDeviceGoodix53x5 *self, const guint8 *payload,
+ gsize len, GError **error)
+{
+ GoodixFdtEventType type;
+ guint16 irq;
+
+ if (len < 2)
+ goto short_event;
+ irq = payload[0] | ((guint16) payload[1] << 8);
+ switch (irq)
+ {
+ case 0:
+ case 1:
+ case 4:
+ case 8:
+ case 0x10:
+ case 0x20:
+ case 0x40:
+ return GOODIX_FDT_EVENT_NONE;
+ case GOODIX_FDT_IRQ_DOWN:
+ type = GOODIX_FDT_EVENT_DOWN;
+ break;
+ case GOODIX_FDT_IRQ_UP:
+ type = GOODIX_FDT_EVENT_UP;
+ break;
+ case GOODIX_FDT_IRQ_REVERSE:
+ case GOODIX_FDT_IRQ_REVERSE_ALT:
+ type = GOODIX_FDT_EVENT_REVERSE;
+ break;
+ case 0x100:
+ type = GOODIX_FDT_EVENT_NONE;
+ break;
+ default:
+ return GOODIX_FDT_EVENT_CONFIG;
+ }
+ if (len < 4 + GOODIX_FDT_BASE_LEN)
+ goto short_event;
+ if (irq == 0x100)
+ self->manual_touch = payload[2] | ((guint16) payload[3] << 8);
+ return type;
+
+short_event:
+ g_set_error_literal (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "Unexpected FDT event length");
+ return GOODIX_FDT_EVENT_NONE;
+}
+
+const GoodixFamily goodix_family_gm168sec = {
+ .link = {
+ .usb_interface = 0,
+ .ep_in = 0x03 | FPI_USB_ENDPOINT_IN,
+ .ep_out = 0x01 | FPI_USB_ENDPOINT_OUT,
+ .frame = goodix_frame_wrapped,
+ .frame_record = goodix_frame_tls_record,
+ .receive = goodix_receive_wrapped,
+ .discard = goodix_drop_pack_stream,
+ },
+ .protocol = {
+ .wake_payload_len = 4,
+ /* McuSetEcCtrl builds [enable, mode, enable]; Dell's 533c driver turns
+ * isolation on with mode 0 when a session starts. */
+ .ec_on_payload = { 0x01, 0x00, 0x01 },
+ .command_budget = goodix_wrapped_command_budget,
+ .retry_write = goodix_gm168sec_retry_write,
+ .repair_arm = goodix_gm168sec_repair_arm,
+ .wake_arm_up = goodix_gm168sec_wake_arm_up,
+ .notice_irq = goodix_gm168sec_notice_irq,
+ .fdt_event = goodix_gm168sec_fdt_event,
+ .ack_timeout_waits_for_data = TRUE,
+ .event = goodix_gm168sec_event,
+ .reply_answers = goodix_gm168sec_reply_answers,
+ .download_succeeded = goodix_gm168sec_download_succeeded,
+ .may_send = goodix_gm168sec_may_send,
+ },
+ .channel = {
+ .name = "TLS",
+ /* Start makes one TLS call and one retry; StartTlsThread, after a failed
+ * read, makes one; LogicEvtTlsConn makes at most two. */
+ .attempts = { .open = 2, .after_failed_read = 1, .reconnect = 2 },
+ .retry_delay_ms = 0,
+ .attempt_new = goodix_tls_attempt_new,
+ .decrypt_frame = goodix_decrypt_frame_tls,
+ .image_error = goodix_tls_image_error,
+ .rearm_after_capture = goodix_gm168sec_rearm_after_capture,
+ .restart_disarms = TRUE,
+ .config_lost = goodix_gm168sec_config_lost,
+ .discard = goodix_tls_discard,
+ },
+ .open_new = goodix_gm168sec_open_new,
+};
diff --git a/libfprint/drivers/goodix53x5/family/gm168sec/gm168sec.h b/libfprint/drivers/goodix53x5/family/gm168sec/gm168sec.h
new file mode 100644
index 0000000..c50e65b
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/family/gm168sec/gm168sec.h
@@ -0,0 +1,39 @@
+/*
+ * Goodix 53x5 driver for libfprint — the GM168SEC family (27c6:533c)
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include "driver-private.h"
+
+/* The prefix before the TLS records of a 0xb2 pack (image data). */
+#define GOODIX_PACK_TLS_DATA_HDR 9
+
+/* 533c ships with the all-zero PSK; this slot holds its SHA-256. */
+#define GOODIX_WRAPPED_PSK_HASH_TYPE 0xbb020001
+#define GOODIX_PSK_HASH_LEN 32
+
+/* Fails without a firmware version, or with one that is not for the
+ * GM168 or GM168SEC platform, as the vendor's SelfCheck does. */
+GError *goodix_gm168sec_check_firmware (const char *firmware);
+/* Returns a new SSM running the 533c bring-up. */
+FpiSsm *goodix_gm168sec_open_new (FpDevice *dev);
+
+/* Returns a new SSM for one TLS handshake attempt. */
+FpiSsm *goodix_tls_attempt_new (FpDevice *dev, GoodixChannelReason reason);
+/* Decrypts the TLS records of an image pack into raw12 bytes in @out. */
+GoodixFrameStatus goodix_decrypt_frame_tls (FpiDeviceGoodix53x5 *self,
+ const guint8 *payload, gsize len,
+ guint8 **out, gsize *out_len);
+/* Counts an undecodable frame; always TRUE. */
+gboolean goodix_tls_image_error (FpiDeviceGoodix53x5 *self);
+/* Frees the TLS session. */
+void goodix_tls_discard (FpiDeviceGoodix53x5 *self);
+/* Drops the receive stream and any partial pack in it. */
+void goodix_drop_pack_stream (FpiDeviceGoodix53x5 *self);
diff --git a/libfprint/drivers/goodix53x5/family/gm168sec/open.c b/libfprint/drivers/goodix53x5/family/gm168sec/open.c
new file mode 100644
index 0000000..59d639c
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/family/gm168sec/open.c
@@ -0,0 +1,224 @@
+/*
+ * Goodix 53x5 driver for libfprint — GM168SEC bring-up
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/commands.h"
+#include "device/session.h"
+#include "family/gm168sec/gm168sec.h"
+
+typedef enum {
+ GOODIX_GM168SEC_OPEN_PROBE,
+ GOODIX_GM168SEC_OPEN_FIRMWARE,
+ GOODIX_GM168SEC_OPEN_FIRMWARE_RETRY,
+ GOODIX_GM168SEC_OPEN_PSK_READ,
+ GOODIX_GM168SEC_OPEN_PSK_CHECK,
+ GOODIX_GM168SEC_OPEN_RESET,
+ GOODIX_GM168SEC_OPEN_CHIP,
+ GOODIX_GM168SEC_OPEN_READ_OTP,
+ GOODIX_GM168SEC_OPEN_PARSE_OTP,
+ GOODIX_GM168SEC_OPEN_CHANNEL,
+ GOODIX_GM168SEC_OPEN_NUM_STATES,
+} GoodixGm168secOpenState;
+
+#ifdef GOODIX53X5_DEBUG
+static const gchar *
+goodix_gm168sec_open_state_name (GoodixGm168secOpenState state)
+{
+ switch (state)
+ {
+ case GOODIX_GM168SEC_OPEN_PROBE:
+ return "ping";
+ case GOODIX_GM168SEC_OPEN_FIRMWARE:
+ case GOODIX_GM168SEC_OPEN_FIRMWARE_RETRY:
+ return "firmware";
+ case GOODIX_GM168SEC_OPEN_PSK_READ:
+ return "early_psk_read";
+ case GOODIX_GM168SEC_OPEN_PSK_CHECK:
+ return "early_psk_check";
+ case GOODIX_GM168SEC_OPEN_RESET:
+ return "reset";
+ case GOODIX_GM168SEC_OPEN_CHIP:
+ return "chip";
+ case GOODIX_GM168SEC_OPEN_READ_OTP:
+ return "read_otp";
+ case GOODIX_GM168SEC_OPEN_PARSE_OTP:
+ return "parse_otp";
+ case GOODIX_GM168SEC_OPEN_CHANNEL:
+ return "gtls_client_hello";
+ case GOODIX_GM168SEC_OPEN_NUM_STATES:
+ default:
+ return "unknown";
+ }
+}
+#endif
+
+static void
+goodix_gm168sec_probe_result (FpiSsm *ssm, FpDevice *dev, guint8 status,
+ gboolean native_zero, GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixGm168secOpenState state = fpi_ssm_get_cur_state (ssm);
+
+ if (error && !native_zero)
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+ if (state == GOODIX_GM168SEC_OPEN_PROBE)
+ {
+ g_clear_error (&error);
+ fpi_ssm_next_state (ssm);
+ return;
+ }
+ if (error)
+ {
+ g_clear_error (&error);
+ if (state == GOODIX_GM168SEC_OPEN_FIRMWARE)
+ fpi_ssm_next_state (ssm);
+ else
+ fpi_ssm_mark_failed (ssm, goodix_gm168sec_check_firmware (NULL));
+ return;
+ }
+ g_free (self->fw_version);
+ self->fw_version = g_strndup ((const gchar *) self->shared_response,
+ sizeof (self->shared_response));
+ error = goodix_gm168sec_check_firmware (self->fw_version);
+ if (error)
+ fpi_ssm_mark_failed (ssm, error);
+ else
+ fpi_ssm_jump_to_state (ssm, GOODIX_GM168SEC_OPEN_PSK_READ);
+}
+
+static void
+goodix_gm168sec_chip_result (FpiSsm *ssm, FpDevice *dev, guint8 status,
+ gboolean native_zero, GError *error)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ const guint8 *payload;
+ gsize len;
+
+ if (fpi_ssm_get_cur_state (ssm) == GOODIX_GM168SEC_OPEN_RESET && (!error || native_zero))
+ {
+ g_clear_error (&error);
+ fpi_ssm_next_state_delayed (ssm, 10);
+ return;
+ }
+ if (error || !goodix_cmd_parse_chip_id_reply (dev, &payload, &len, &error))
+ {
+ fpi_ssm_mark_failed (ssm, error);
+ return;
+ }
+ if (len != 4)
+ {
+ fpi_ssm_mark_failed (ssm, fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_PROTO, "Unexpected chip ID reply length: %zu", len));
+ return;
+ }
+ self->chip_id = goodix_crypto_decode_u32 (payload);
+ if (!goodix_milan_runtime_subtype_for_chip (self->chip_id, &self->milan_sensor_subtype))
+ fpi_ssm_mark_failed (ssm, fpi_device_error_new_msg (
+ FP_DEVICE_ERROR_NOT_SUPPORTED, "Unsupported chip 0x%08x", self->chip_id));
+ else
+ fpi_ssm_next_state (ssm);
+}
+
+/* Brings a 533c up to an established TLS session in the vendor's order:
+ * SelfCheck's firmware reads, the PSK check the vendor makes before it
+ * resets the sensor, the chip ID read after a reset asking for the IRQ
+ * reply, the OTP, then the handshake. The driver never writes a PSK here,
+ * so one that does not match fails open. */
+static void
+goodix_gm168sec_open_handler (FpiSsm *ssm, FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ GoodixGm168secOpenState state = fpi_ssm_get_cur_state (ssm);
+
+ goodix_debug_timing_open_state (self, dev, goodix_gm168sec_open_state_name (state),
+ g_get_monotonic_time ());
+
+ switch (state)
+ {
+ case GOODIX_GM168SEC_OPEN_PROBE:
+ case GOODIX_GM168SEC_OPEN_FIRMWARE:
+ case GOODIX_GM168SEC_OPEN_FIRMWARE_RETRY:
+ goodix_cmd_probe (ssm, dev, state != GOODIX_GM168SEC_OPEN_PROBE,
+ goodix_gm168sec_probe_result);
+ break;
+
+ case GOODIX_GM168SEC_OPEN_PSK_READ:
+ {
+ g_autoptr(GError) error = NULL;
+
+ if (!goodix_load_psk (self, &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ goodix_cmd_preset_read (ssm, dev, GOODIX_WRAPPED_PSK_HASH_TYPE, GOODIX_PSK_HASH_LEN);
+ }
+ break;
+
+ case GOODIX_GM168SEC_OPEN_PSK_CHECK:
+ {
+ GError *error = NULL;
+
+ if (!goodix_require_current_psk (dev, GOODIX_WRAPPED_PSK_HASH_TYPE, &error))
+ fpi_ssm_mark_failed (ssm, error);
+ else
+ fpi_ssm_next_state (ssm);
+ }
+ break;
+
+ case GOODIX_GM168SEC_OPEN_RESET:
+ self->profile9_fdt.drift_anchor_empty = TRUE;
+ goodix_health_reset (&self->health);
+ self->capture_callback_pending = FALSE;
+ goodix_cmd_reset_sensor (ssm, dev, TRUE, goodix_gm168sec_chip_result);
+ break;
+
+ case GOODIX_GM168SEC_OPEN_CHIP:
+ goodix_cmd_read_chip_id (ssm, dev, goodix_gm168sec_chip_result);
+ break;
+
+ case GOODIX_GM168SEC_OPEN_READ_OTP:
+ goodix_cmd_read_otp (ssm, dev);
+ break;
+
+ case GOODIX_GM168SEC_OPEN_PARSE_OTP:
+ {
+ g_autoptr(GError) error = NULL;
+
+ if (!goodix_open_parse_otp (dev, &error))
+ {
+ fpi_ssm_mark_failed (ssm, g_steal_pointer (&error));
+ return;
+ }
+ fpi_ssm_next_state (ssm);
+ }
+ break;
+
+ case GOODIX_GM168SEC_OPEN_CHANNEL:
+ goodix_open_channel (ssm, dev);
+ break;
+
+ case GOODIX_GM168SEC_OPEN_NUM_STATES:
+ g_assert_not_reached ();
+ break;
+ }
+}
+
+FpiSsm *
+goodix_gm168sec_open_new (FpDevice *dev)
+{
+ return fpi_ssm_new (dev, goodix_gm168sec_open_handler, GOODIX_GM168SEC_OPEN_NUM_STATES);
+}
diff --git a/libfprint/drivers/goodix53x5/family/gm168sec/tls.c b/libfprint/drivers/goodix53x5/family/gm168sec/tls.c
new file mode 100644
index 0000000..af909f9
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/family/gm168sec/tls.c
@@ -0,0 +1,236 @@
+/*
+ * Goodix 53x5 driver for libfprint — TLS-PSK for wrapped sensors
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "family/gm168sec/tls.h"
+
+#include <openssl/err.h>
+#include <openssl/ssl.h>
+
+/* The suite the sensor negotiates with a stock `openssl s_server -psk`. */
+#define GOODIX_TLS_CIPHER "PSK-AES128-CBC-SHA256"
+#define GOODIX_TLS_MAX_PSK 64
+/* McuStartTls gives up after this many handshake calls. Each of its calls
+ * reads all the input there is and ends in one empty 50 ms wait, so only an
+ * empty wait uses one up. */
+#define GOODIX_TLS_MAX_HANDSHAKE_CALLS 10
+
+struct _GoodixTls
+{
+ SSL_CTX *ctx;
+ SSL *ssl;
+ BIO *in; /* records from the sensor; owned by ssl */
+ BIO *out; /* records for the sensor; owned by ssl */
+ guint8 psk[GOODIX_TLS_MAX_PSK];
+ gsize psk_len;
+ guint handshake_calls;
+};
+
+static unsigned int
+goodix_tls_psk_cb (SSL *ssl, const char *identity, unsigned char *psk,
+ unsigned int max_psk_len)
+{
+ GoodixTls *tls = SSL_get_app_data (ssl);
+
+ if (g_strcmp0 (identity, "Client_identity") != 0 || tls->psk_len > max_psk_len)
+ return 0;
+ memcpy (psk, tls->psk, tls->psk_len);
+ return tls->psk_len;
+}
+
+static void
+goodix_tls_set_error (GError **error, const char *what)
+{
+ char buf[256] = "unknown error";
+ unsigned long code = ERR_get_error ();
+
+ if (code)
+ ERR_error_string_n (code, buf, sizeof (buf));
+ ERR_clear_error ();
+ g_set_error (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "TLS %s failed: %s", what, buf);
+}
+
+GoodixTls *
+goodix_tls_new (const guint8 *psk, gsize psk_len, GError **error)
+{
+ GoodixTls *tls;
+
+ g_return_val_if_fail (psk_len <= GOODIX_TLS_MAX_PSK, NULL);
+ tls = g_new0 (GoodixTls, 1);
+ memcpy (tls->psk, psk, psk_len);
+ tls->psk_len = psk_len;
+
+ tls->ctx = SSL_CTX_new (TLS_server_method ());
+ if (!tls->ctx ||
+ !SSL_CTX_set_min_proto_version (tls->ctx, TLS1_2_VERSION) ||
+ !SSL_CTX_set_max_proto_version (tls->ctx, TLS1_2_VERSION) ||
+ !SSL_CTX_set_cipher_list (tls->ctx, GOODIX_TLS_CIPHER))
+ {
+ goodix_tls_set_error (error, "setup");
+ goodix_tls_free (tls);
+ return NULL;
+ }
+ SSL_CTX_set_options (tls->ctx, SSL_OP_NO_TICKET | SSL_OP_NO_RENEGOTIATION);
+ SSL_CTX_set_psk_server_callback (tls->ctx, goodix_tls_psk_cb);
+
+ tls->ssl = SSL_new (tls->ctx);
+ tls->in = BIO_new (BIO_s_mem ());
+ tls->out = BIO_new (BIO_s_mem ());
+ if (!tls->ssl || !tls->in || !tls->out)
+ {
+ BIO_free (tls->in);
+ BIO_free (tls->out);
+ tls->in = tls->out = NULL;
+ goodix_tls_set_error (error, "setup");
+ goodix_tls_free (tls);
+ return NULL;
+ }
+ /* An empty input BIO means "wait for more", not end of stream. */
+ BIO_set_mem_eof_return (tls->in, -1);
+ SSL_set_bio (tls->ssl, tls->in, tls->out);
+ SSL_set_app_data (tls->ssl, tls);
+ SSL_set_accept_state (tls->ssl);
+ return tls;
+}
+
+void
+goodix_tls_free (GoodixTls *tls)
+{
+ if (!tls)
+ return;
+ SSL_free (tls->ssl);
+ SSL_CTX_free (tls->ctx);
+ OPENSSL_cleanse (tls->psk, sizeof (tls->psk));
+ g_free (tls);
+}
+
+static GBytes *
+goodix_tls_take_output (GoodixTls *tls)
+{
+ char *data;
+ long len = BIO_get_mem_data (tls->out, &data);
+ GBytes *out;
+
+ if (len <= 0)
+ return NULL;
+ out = g_bytes_new (data, len);
+ (void) BIO_reset (tls->out);
+ return out;
+}
+
+gboolean
+goodix_tls_handshake (GoodixTls *tls,
+ const guint8 *in,
+ gsize in_len,
+ GBytes **out,
+ GError **error)
+{
+ int ret;
+
+ *out = NULL;
+ if (!in_len && ++tls->handshake_calls > GOODIX_TLS_MAX_HANDSHAKE_CALLS)
+ {
+ g_set_error (error, FP_DEVICE_ERROR, FP_DEVICE_ERROR_PROTO,
+ "TLS handshake did not finish in %d empty waits",
+ GOODIX_TLS_MAX_HANDSHAKE_CALLS);
+ return FALSE;
+ }
+ if (in_len && BIO_write (tls->in, in, in_len) != (int) in_len)
+ {
+ goodix_tls_set_error (error, "input");
+ return FALSE;
+ }
+
+ ret = SSL_do_handshake (tls->ssl);
+ if (ret == 1 || SSL_get_error (tls->ssl, ret) == SSL_ERROR_WANT_READ)
+ {
+ *out = goodix_tls_take_output (tls);
+ return TRUE;
+ }
+
+ goodix_tls_set_error (error, "handshake");
+ return FALSE;
+}
+
+gboolean
+goodix_tls_established (GoodixTls *tls)
+{
+ return SSL_is_init_finished (tls->ssl);
+}
+
+gboolean
+goodix_tls_handshake_pending (GoodixTls *tls)
+{
+ return tls->handshake_calls < GOODIX_TLS_MAX_HANDSHAKE_CALLS;
+}
+
+/* Checks whether @records is a run of whole TLS records, each its header
+ * and the length that header announces. OpenSSL would keep a cut
+ * record, even a bare header, for the next call and fail that one instead. */
+static gboolean
+goodix_tls_records_whole (const guint8 *records, gsize len)
+{
+ gsize offset = 0;
+
+ while (offset + GOODIX_TLS_RECORD_HEADER <= len)
+ {
+ const guint8 *header = records + offset;
+
+ offset += GOODIX_TLS_RECORD_HEADER + (header[3] << 8 | header[4]);
+ }
+ return offset == len;
+}
+
+guint8 *
+goodix_tls_decrypt (GoodixTls *tls,
+ const guint8 *records,
+ gsize records_len,
+ gsize *out_len)
+{
+ GByteArray *plain = g_byte_array_new ();
+ guint8 buf[16 * 1024];
+ gboolean ok;
+ int ret = 0;
+
+ if (!goodix_tls_records_whole (records, records_len))
+ {
+ fp_warn ("TLS record is incomplete");
+ g_byte_array_free (plain, TRUE);
+ return NULL;
+ }
+ ok = BIO_write (tls->in, records, records_len) == (int) records_len;
+ while (ok && (ret = SSL_read (tls->ssl, buf, sizeof (buf))) > 0)
+ g_byte_array_append (plain, buf, ret);
+ OPENSSL_cleanse (buf, sizeof (buf));
+
+ if (ok && SSL_get_error (tls->ssl, ret) != SSL_ERROR_WANT_READ)
+ {
+ fp_warn ("TLS record did not authenticate");
+ ok = FALSE;
+ }
+ else if (ok && !plain->len)
+ {
+ fp_warn ("TLS records carried no data");
+ ok = FALSE;
+ }
+ ERR_clear_error ();
+ if (!ok)
+ {
+ OPENSSL_cleanse (plain->data, plain->len);
+ g_byte_array_free (plain, TRUE);
+ return NULL;
+ }
+
+ *out_len = plain->len;
+ return g_byte_array_free (plain, FALSE);
+}
diff --git a/libfprint/drivers/goodix53x5/family/gm168sec/tls.h b/libfprint/drivers/goodix53x5/family/gm168sec/tls.h
new file mode 100644
index 0000000..0f2a0b3
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/family/gm168sec/tls.h
@@ -0,0 +1,45 @@
+/*
+ * Goodix 53x5 driver for libfprint — TLS-PSK for wrapped sensors
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include <glib.h>
+
+/* A TLS record's header: content type, version, and its big-endian length. */
+#define GOODIX_TLS_RECORD_HEADER 5
+
+/* The host (server) end of a wrapped sensor's TLS 1.2-PSK session: the one
+ * place its records are produced and authenticated; transport only moves them. */
+typedef struct _GoodixTls GoodixTls;
+
+GoodixTls *goodix_tls_new (const guint8 *psk,
+ gsize psk_len,
+ GError **error);
+void goodix_tls_free (GoodixTls *tls);
+
+/* Advances the handshake with the sensor's records in @in, which may be
+ * empty; @out receives the records to send back, or NULL. Fails, and
+ * leaves the session unusable, when the sensor's records are rejected or
+ * the handshake takes more than ten calls. */
+gboolean goodix_tls_handshake (GoodixTls *tls,
+ const guint8 *in,
+ gsize in_len,
+ GBytes **out,
+ GError **error);
+gboolean goodix_tls_established (GoodixTls *tls);
+gboolean goodix_tls_handshake_pending (GoodixTls *tls);
+
+/* Returns the plaintext of application-data records, or NULL when one does
+ * not authenticate or the last is incomplete; either leaves the session
+ * unusable. */
+guint8 *goodix_tls_decrypt (GoodixTls *tls,
+ const guint8 *records,
+ gsize records_len,
+ gsize *out_len);
diff --git a/libfprint/drivers/goodix53x5/goodix53x5.c b/libfprint/drivers/goodix53x5/goodix53x5.c
new file mode 100644
index 0000000..4547070
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/goodix53x5.c
@@ -0,0 +1,184 @@
+/*
+ * Goodix 53x5 driver for libfprint
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "driver-private.h"
+#include "device/session.h"
+#include "device/enroll.h"
+#include "device/auth.h"
+#include "device/persistence.h"
+#include "device/transport.h"
+#include "device/scan.h"
+
+#include <string.h>
+
+G_DEFINE_TYPE (FpiDeviceGoodix53x5, fpi_device_goodix53x5,
+ FP_TYPE_DEVICE)
+
+/* ========================================================================
+ * FpDevice virtual methods
+ * ======================================================================== */
+
+static void
+goodix_open (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ self->open_recovery_attempted = FALSE;
+ self->open_usb_reset_required = FALSE;
+ g_clear_object (&self->session_cancel);
+ self->session_cancel = g_cancellable_new ();
+ self->session_suspended = FALSE;
+ self->suspend_pending = FALSE;
+ goodix_start_open_ssm (dev);
+}
+
+static void
+goodix_close (FpDevice *dev)
+{
+ goodix_session_close (dev);
+}
+
+static void
+goodix_enroll (FpDevice *dev)
+{
+ goodix_session_start_action (dev);
+}
+
+static void
+goodix_verify (FpDevice *dev)
+{
+ goodix_session_start_action (dev);
+}
+
+static void
+goodix_identify (FpDevice *dev)
+{
+ goodix_session_start_action (dev);
+}
+
+static void
+goodix_suspend (FpDevice *dev)
+{
+ goodix_session_suspend (dev);
+}
+
+static void
+goodix_resume (FpDevice *dev)
+{
+ goodix_session_resume (dev);
+}
+
+static void
+goodix_cancel (FpDevice *dev)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+
+ if (goodix_session_cancel_pending_action (dev))
+ return;
+
+ if (self->cancel)
+ {
+ self->action_epoch++;
+ g_cancellable_cancel (self->cancel);
+ }
+}
+
+static void
+goodix_removed (FpDevice *dev, GParamSpec *pspec, gpointer data)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (dev);
+ gboolean removed = FALSE;
+
+ g_object_get (dev, "removed", &removed, NULL);
+ if (!removed || (!self->session_open && !self->task_ssm))
+ return;
+ self->needs_reinit = TRUE;
+ if (self->session_cancel)
+ g_cancellable_cancel (self->session_cancel);
+ goodix_scan_stop_coordinator (
+ dev, fpi_device_error_new (FP_DEVICE_ERROR_REMOVED));
+}
+
+/* ========================================================================
+ * GObject boilerplate
+ * ======================================================================== */
+
+static void
+fpi_device_goodix53x5_init (FpiDeviceGoodix53x5 *self)
+{
+#ifdef GOODIX53X5_DEBUG
+ g_autofree gchar *capture_session_id = g_uuid_string_random ();
+
+ g_strlcpy (self->debug_capture_session_id, capture_session_id,
+ sizeof (self->debug_capture_session_id));
+#endif
+ memset (self->psk, 0, sizeof (self->psk));
+ self->profile9_fdt.drift_anchor_empty = TRUE;
+ self->session_cancel = g_cancellable_new ();
+ g_signal_connect (self, "notify::removed", G_CALLBACK (goodix_removed), NULL);
+}
+
+static const FpIdEntry goodix53x5_id_table[] = {
+ { .vid = 0x27c6, .pid = 0x533c, .driver_data = GOODIX_FAMILY_GM168SEC },
+ { .vid = 0, .pid = 0, .driver_data = 0 },
+};
+
+static void
+goodix_finalize (GObject *object)
+{
+ FpiDeviceGoodix53x5 *self = FPI_DEVICE_GOODIX53X5 (object);
+
+ goodix_milan_generation_invalidate (&self->milan_retained_generation);
+ if (goodix_family (self)->link.discard)
+ goodix_family (self)->link.discard (self);
+ if (goodix_family (self)->channel.discard)
+ goodix_family (self)->channel.discard (self);
+ g_clear_pointer (&self->hardware_reference, g_free);
+ g_clear_object (&self->session_cancel);
+ G_OBJECT_CLASS (fpi_device_goodix53x5_parent_class)->finalize (object);
+}
+
+static void
+fpi_device_goodix53x5_class_init (FpiDeviceGoodix53x5Class *klass)
+{
+ FpDeviceClass *dev_class = FP_DEVICE_CLASS (klass);
+
+ G_OBJECT_CLASS (klass)->finalize = goodix_finalize;
+ dev_class->id = "goodix53x5";
+ dev_class->full_name = "Goodix HTK32 Fingerprint Sensor";
+ dev_class->type = FP_DEVICE_TYPE_USB;
+ dev_class->scan_type = FP_SCAN_TYPE_PRESS;
+ dev_class->id_table = goodix53x5_id_table;
+ dev_class->nr_enroll_stages = GOODIX_ENROLL_SAMPLES;
+ /* Native Milan has no equivalent time-based thermal cutoff. */
+ dev_class->temp_hot_seconds = -1;
+ dev_class->features = FP_DEVICE_FEATURE_VERIFY | FP_DEVICE_FEATURE_IDENTIFY;
+
+ dev_class->open = goodix_open;
+ dev_class->close = goodix_close;
+ dev_class->enroll = goodix_enroll;
+ dev_class->verify = goodix_verify;
+ dev_class->identify = goodix_identify;
+ dev_class->cancel = goodix_cancel;
+ dev_class->suspend = goodix_suspend;
+ dev_class->resume = goodix_resume;
+}
diff --git a/libfprint/drivers/goodix53x5/goodix53x5.h b/libfprint/drivers/goodix53x5/goodix53x5.h
new file mode 100644
index 0000000..b4677da
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/goodix53x5.h
@@ -0,0 +1,26 @@
+/*
+ * Goodix 53x5 driver for libfprint
+ * Copyright (C) 2024 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#pragma once
+
+#include "fpi-device.h"
+
+#define FPI_TYPE_DEVICE_GOODIX53X5 (fpi_device_goodix53x5_get_type ())
+G_DECLARE_FINAL_TYPE (FpiDeviceGoodix53x5, fpi_device_goodix53x5, FPI,
+ DEVICE_GOODIX53X5, FpDevice)
diff --git a/libfprint/drivers/goodix53x5/meson.build b/libfprint/drivers/goodix53x5/meson.build
new file mode 100644
index 0000000..96dc3f1
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/meson.build
@@ -0,0 +1,66 @@
+goodix53x5_sources = files(
+ 'milan/antifake/classifier.c',
+ 'milan/antifake/construction.c',
+ 'milan/antifake/feature.c',
+ 'milan/antifake/mask.c',
+ 'milan/antifake/morphology.c',
+ 'milan/antifake/pair.c',
+ 'milan/antifake/signal.c',
+ 'device/auth.c',
+ 'device/base.c',
+ 'device/calibration.c',
+ 'device/commands.c',
+ 'device/crypto.c',
+ 'family/gm168sec/channel.c',
+ 'family/gm168sec/gm168sec.c',
+ 'family/gm168sec/open.c',
+ 'family/gm168sec/tls.c',
+ 'device/enroll.c',
+ 'device/health.c',
+ 'milan/enrollment/propagation.c',
+ 'milan/enrollment/template.c',
+ 'milan/feature/enhancement.c',
+ 'milan/feature/extraction.c',
+ 'milan/feature/extrema.c',
+ 'milan/feature/mask.c',
+ 'milan/feature/materialization.c',
+ 'milan/feature/record.c',
+ 'device/image.c',
+ 'device/persistence.c',
+ 'milan/match/admission.c',
+ 'milan/match/candidate.c',
+ 'milan/match/correspondence.c',
+ 'milan/match/fallback.c',
+ 'milan/match/geometry.c',
+ 'milan/match/info.c',
+ 'milan/match/lifecycle.c',
+ 'milan/match/overlap.c',
+ 'milan/match/policy.c',
+ 'milan/match/rescue.c',
+ 'milan/match/score.c',
+ 'milan/match/selection.c',
+ 'milan/match/study.c',
+ 'milan/match/match.c',
+ 'milan/core.c',
+ 'milan/debug-hooks.c',
+ 'milan/preprocess/classification.c',
+ 'milan/preprocess/gain.c',
+ 'milan/preprocess/selection.c',
+ 'milan/preprocess/validity.c',
+ 'milan/print.c',
+ 'device/proto.c',
+ 'milan/relations.c',
+ 'milan/runtime.c',
+ 'device/scan.c',
+ 'device/session.c',
+ 'milan/study/policy.c',
+ 'milan/study/queue.c',
+ 'milan/study/study.c',
+ 'milan/template/codec.c',
+ 'milan/template/lifecycle.c',
+ 'milan/transform.c',
+ 'device/transport.c',
+ 'goodix53x5.c',
+)
+
+goodix53x5_cflags = [ '-I' + meson.current_source_dir() ]
diff --git a/libfprint/drivers/goodix53x5/milan/antifake/antifake.h b/libfprint/drivers/goodix53x5/milan/antifake/antifake.h
new file mode 100644
index 0000000..09dd551
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/antifake/antifake.h
@@ -0,0 +1,337 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan anti-fake interface
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+
+#define GOODIX_MILAN_ANTIFAKE_AMBIGUOUS 1
+#define GOODIX_MILAN_ANTIFAKE_SIZE 0x1abcU
+#define GOODIX_MILAN_ANTIFAKE_DEFINED_MATERIAL_SIZE GOODIX_MILAN_ANTIFAKE_SIZE
+#define GOODIX_MILAN_ANTIFAKE_RECORD_SIZE 48U
+#define GOODIX_MILAN_ANTIFAKE_RECORD_CAPACITY 100U
+#define GOODIX_MILAN_ANTIFAKE_RECORDS_OFFSET 0U
+#define GOODIX_MILAN_ANTIFAKE_RECORD_X_OFFSET 0U
+#define GOODIX_MILAN_ANTIFAKE_RECORD_Y_OFFSET 4U
+#define GOODIX_MILAN_ANTIFAKE_RECORD_DATA_8_OFFSET 8U
+#define GOODIX_MILAN_ANTIFAKE_RECORD_DATA_16_OFFSET 16U
+#define GOODIX_MILAN_ANTIFAKE_RECORD_DATA_24_OFFSET 24U
+#define GOODIX_MILAN_ANTIFAKE_RECORD_DATA_32_OFFSET 32U
+#define GOODIX_MILAN_ANTIFAKE_RECORD_DATA_40_OFFSET 40U
+#define GOODIX_MILAN_ANTIFAKE_RECORD_DATA_44_OFFSET 44U
+#define GOODIX_MILAN_ANTIFAKE_RECORDS_SIZE \
+ (GOODIX_MILAN_ANTIFAKE_RECORD_SIZE * GOODIX_MILAN_ANTIFAKE_RECORD_CAPACITY)
+#define GOODIX_MILAN_ANTIFAKE_CANDIDATE_COUNT_OFFSET 0x12c0U
+#define GOODIX_MILAN_ANTIFAKE_TEXTURE_OFFSET 0x12c4U
+#define GOODIX_MILAN_ANTIFAKE_MEAN_OFFSET 0x12c8U
+#define GOODIX_MILAN_ANTIFAKE_VARIATION_OFFSET 0x12ccU
+#define GOODIX_MILAN_ANTIFAKE_BOUNDARY_OFFSET 0x12d0U
+#define GOODIX_MILAN_ANTIFAKE_MODEL_OFFSET 0x12d8U
+#define GOODIX_MILAN_ANTIFAKE_MASK_OFFSET 0x12dcU
+#define GOODIX_MILAN_ANTIFAKE_MASK_SIZE 2000U
+#define GOODIX_MILAN_ANTIFAKE_CALIBRATION_SCALAR_OFFSET 0x1aacU
+#define GOODIX_MILAN_ANTIFAKE_THRESHOLD_OFFSET 0x1ab0U
+#define GOODIX_MILAN_ANTIFAKE_PAIR_SCORE_OFFSET 0x1ab4U
+
+typedef struct _GoodixMilanFeatureRecord GoodixMilanFeatureRecord;
+
+typedef struct
+{
+ uint8_t bytes[GOODIX_MILAN_ANTIFAKE_SIZE];
+} GoodixMilanAntifakeBlob;
+
+_Static_assert (sizeof (GoodixMilanAntifakeBlob) == GOODIX_MILAN_ANTIFAKE_SIZE,
+ "Milan anti-fake blob size changed");
+_Static_assert (_Alignof (GoodixMilanAntifakeBlob) == _Alignof (uint8_t),
+ "Milan anti-fake blob alignment changed");
+_Static_assert (offsetof (GoodixMilanAntifakeBlob, bytes) == 0,
+ "Milan anti-fake blob data moved");
+_Static_assert (GOODIX_MILAN_ANTIFAKE_RECORDS_SIZE ==
+ GOODIX_MILAN_ANTIFAKE_CANDIDATE_COUNT_OFFSET,
+ "Milan anti-fake record extent changed");
+_Static_assert (GOODIX_MILAN_ANTIFAKE_RECORD_DATA_44_OFFSET + 4U ==
+ GOODIX_MILAN_ANTIFAKE_RECORD_SIZE,
+ "Milan anti-fake record layout changed");
+_Static_assert (GOODIX_MILAN_ANTIFAKE_MASK_OFFSET +
+ GOODIX_MILAN_ANTIFAKE_MASK_SIZE ==
+ GOODIX_MILAN_ANTIFAKE_CALIBRATION_SCALAR_OFFSET,
+ "Milan anti-fake mask extent changed");
+_Static_assert (GOODIX_MILAN_ANTIFAKE_PAIR_SCORE_OFFSET + sizeof (int32_t) <=
+ GOODIX_MILAN_ANTIFAKE_SIZE,
+ "Milan anti-fake pair score exceeds the blob");
+
+static inline uint8_t *
+goodix_milan_antifake_data (GoodixMilanAntifakeBlob *blob)
+{
+ return blob ? blob->bytes : NULL;
+}
+
+static inline const uint8_t *
+goodix_milan_antifake_const_data (const GoodixMilanAntifakeBlob *blob)
+{
+ return blob ? blob->bytes : NULL;
+}
+
+static inline uint8_t *
+goodix_milan_antifake_record (GoodixMilanAntifakeBlob *blob,
+ size_t index)
+{
+ return blob->bytes + GOODIX_MILAN_ANTIFAKE_RECORDS_OFFSET +
+ index * GOODIX_MILAN_ANTIFAKE_RECORD_SIZE;
+}
+
+static inline const uint8_t *
+goodix_milan_antifake_const_record (const GoodixMilanAntifakeBlob *blob,
+ size_t index)
+{
+ return blob->bytes + GOODIX_MILAN_ANTIFAKE_RECORDS_OFFSET +
+ index * GOODIX_MILAN_ANTIFAKE_RECORD_SIZE;
+}
+
+static inline int32_t
+goodix_milan_antifake_record_x (const uint8_t *record)
+{
+ int32_t value;
+
+ memcpy (&value, record + GOODIX_MILAN_ANTIFAKE_RECORD_X_OFFSET,
+ sizeof (value));
+ return value;
+}
+
+static inline void
+goodix_milan_antifake_set_record_x (uint8_t *record,
+ int32_t value)
+{
+ memcpy (record + GOODIX_MILAN_ANTIFAKE_RECORD_X_OFFSET, &value,
+ sizeof (value));
+}
+
+static inline int32_t
+goodix_milan_antifake_record_y (const uint8_t *record)
+{
+ int32_t value;
+
+ memcpy (&value, record + GOODIX_MILAN_ANTIFAKE_RECORD_Y_OFFSET,
+ sizeof (value));
+ return value;
+}
+
+static inline void
+goodix_milan_antifake_set_record_y (uint8_t *record,
+ int32_t value)
+{
+ memcpy (record + GOODIX_MILAN_ANTIFAKE_RECORD_Y_OFFSET, &value,
+ sizeof (value));
+}
+
+static inline uint8_t *
+goodix_milan_antifake_mask (GoodixMilanAntifakeBlob *blob)
+{
+ return blob->bytes + GOODIX_MILAN_ANTIFAKE_MASK_OFFSET;
+}
+
+static inline const uint8_t *
+goodix_milan_antifake_const_mask (const GoodixMilanAntifakeBlob *blob)
+{
+ return blob->bytes + GOODIX_MILAN_ANTIFAKE_MASK_OFFSET;
+}
+
+static inline uint32_t
+goodix_milan_antifake_candidate_count (const GoodixMilanAntifakeBlob *blob)
+{
+ uint32_t value;
+
+ memcpy (&value, blob->bytes + GOODIX_MILAN_ANTIFAKE_CANDIDATE_COUNT_OFFSET,
+ sizeof (value));
+ return value;
+}
+
+static inline void
+goodix_milan_antifake_set_candidate_count (GoodixMilanAntifakeBlob *blob,
+ uint32_t value)
+{
+ memcpy (blob->bytes + GOODIX_MILAN_ANTIFAKE_CANDIDATE_COUNT_OFFSET, &value,
+ sizeof (value));
+}
+
+#define GOODIX_MILAN_ANTIFAKE_SCALAR_ACCESSORS(name, offset) \
+ static inline int32_t \
+ goodix_milan_antifake_ ## name (const GoodixMilanAntifakeBlob * blob) \
+ { \
+ int32_t value; \
+ memcpy (&value, blob->bytes + (offset), sizeof (value)); \
+ return value; \
+ } \
+ static inline void \
+ goodix_milan_antifake_set_ ## name (GoodixMilanAntifakeBlob * blob, \
+ int32_t value) \
+ { \
+ memcpy (blob->bytes + (offset), &value, sizeof (value)); \
+ }
+
+GOODIX_MILAN_ANTIFAKE_SCALAR_ACCESSORS (texture,
+ GOODIX_MILAN_ANTIFAKE_TEXTURE_OFFSET)
+GOODIX_MILAN_ANTIFAKE_SCALAR_ACCESSORS (mean,
+ GOODIX_MILAN_ANTIFAKE_MEAN_OFFSET)
+GOODIX_MILAN_ANTIFAKE_SCALAR_ACCESSORS (variation,
+ GOODIX_MILAN_ANTIFAKE_VARIATION_OFFSET)
+GOODIX_MILAN_ANTIFAKE_SCALAR_ACCESSORS (boundary,
+ GOODIX_MILAN_ANTIFAKE_BOUNDARY_OFFSET)
+GOODIX_MILAN_ANTIFAKE_SCALAR_ACCESSORS (model,
+ GOODIX_MILAN_ANTIFAKE_MODEL_OFFSET)
+GOODIX_MILAN_ANTIFAKE_SCALAR_ACCESSORS (
+ calibration_scalar, GOODIX_MILAN_ANTIFAKE_CALIBRATION_SCALAR_OFFSET)
+GOODIX_MILAN_ANTIFAKE_SCALAR_ACCESSORS (threshold,
+ GOODIX_MILAN_ANTIFAKE_THRESHOLD_OFFSET)
+GOODIX_MILAN_ANTIFAKE_SCALAR_ACCESSORS (pair_score,
+ GOODIX_MILAN_ANTIFAKE_PAIR_SCORE_OFFSET)
+
+#undef GOODIX_MILAN_ANTIFAKE_SCALAR_ACCESSORS
+
+typedef enum {
+ GOODIX_MILAN_ANTIFAKE_BOUNDARY_NOT_EVALUATED,
+ GOODIX_MILAN_ANTIFAKE_BOUNDARY_STABLE,
+ GOODIX_MILAN_ANTIFAKE_BOUNDARY_AMBIGUOUS,
+} GoodixMilanAntifakeBoundaryClass;
+
+typedef struct
+{
+ GoodixMilanAntifakeBoundaryClass classification;
+ uint32_t zero_candidate_count;
+ uint32_t nonzero_candidate_count;
+ GoodixMilanAntifakeBlob zero_projection;
+ GoodixMilanAntifakeBlob nonzero_projection;
+} GoodixMilanAntifakeBoundaryResult;
+
+int goodix_milan_antifake_residual (const uint16_t *calibration,
+ const uint16_t *raw_frame,
+ size_t rows,
+ size_t columns,
+ int32_t sensor_offset,
+ uint16_t chip_type,
+ uint16_t *residual);
+
+int goodix_milan_antifake_impulse_filter (uint16_t *residual,
+ size_t rows,
+ size_t columns,
+ int32_t *threshold);
+
+int goodix_milan_antifake_statistics (const uint16_t *residual,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ int32_t *texture,
+ int32_t *mean);
+
+int goodix_milan_antifake_block_variation (const uint16_t *residual,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ size_t block_size,
+ int32_t *variation);
+
+int goodix_milan_antifake_model_score (const int32_t vector[51],
+ int32_t *score);
+
+int goodix_milan_antifake_model_vector (const uint16_t *residual,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ size_t border,
+ int32_t vector[51]);
+
+int goodix_milan_antifake_class_map (const uint8_t *image,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ uint8_t *classes);
+
+int goodix_milan_antifake_boundary_score (const uint16_t *residual,
+ const uint8_t *classes,
+ size_t rows,
+ size_t columns,
+ int32_t *score);
+
+int goodix_milan_antifake_build (const uint16_t *calibration,
+ const uint16_t *raw_frame,
+ const uint8_t *classification_plane,
+ const uint8_t *feature_mask,
+ size_t feature_mask_size,
+ size_t rows,
+ size_t columns,
+ uint16_t t_code,
+ uint16_t dac_high,
+ uint16_t dac_low,
+ uint16_t chip_type,
+ int32_t calibration_scalar,
+ GoodixMilanAntifakeBlob *antifake,
+ size_t antifake_size);
+
+int goodix_milan_antifake_build_with_boundary (const uint16_t *calibration,
+ const uint16_t *raw_frame,
+ const uint8_t *classification_plane,
+ const uint8_t *feature_mask,
+ size_t feature_mask_size,
+ size_t rows,
+ size_t columns,
+ uint16_t t_code,
+ uint16_t dac_high,
+ uint16_t dac_low,
+ uint16_t chip_type,
+ int32_t calibration_scalar,
+ GoodixMilanAntifakeBlob *antifake,
+ size_t antifake_size,
+ GoodixMilanAntifakeBoundaryResult *boundary_result);
+
+int goodix_milan_antifake_score_pair (const GoodixMilanAntifakeBlob *prior,
+ size_t prior_size,
+ const GoodixMilanAntifakeBlob *current,
+ size_t current_size,
+ const int32_t current_to_prior[6],
+ int32_t *score);
+
+int goodix_milan_antifake_pair_metrics (const GoodixMilanAntifakeBlob *prior,
+ size_t prior_size,
+ const GoodixMilanAntifakeBlob *current,
+ size_t current_size,
+ const int32_t current_to_prior[6],
+ int32_t metrics[5]);
+
+int goodix_milan_antifake_feature_update (GoodixMilanAntifakeBlob *antifake,
+ size_t antifake_size,
+ const uint16_t *source,
+ size_t rows,
+ size_t columns);
+
+int goodix_milan_antifake_feature_maps (const uint16_t *source,
+ size_t rows,
+ size_t columns,
+ uint8_t *dense_orientation,
+ uint32_t *magnitude,
+ int16_t *gradient_orientation);
+
+int goodix_milan_antifake_feature_record (const uint8_t *dense_orientation,
+ const uint32_t *magnitude,
+ const int16_t *gradient_orientation,
+ size_t rows,
+ size_t columns,
+ int32_t x,
+ int32_t y,
+ GoodixMilanFeatureRecord *record);
+
+int goodix_milan_antifake_build_mask (const uint8_t *feature_mask,
+ size_t feature_mask_size,
+ size_t rows,
+ size_t columns,
+ uint8_t *mask,
+ uint8_t *packed,
+ size_t packed_size);
diff --git a/libfprint/drivers/goodix53x5/milan/antifake/classifier.c b/libfprint/drivers/goodix53x5/milan/antifake/classifier.c
new file mode 100644
index 0000000..efb4c77
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/antifake/classifier.c
@@ -0,0 +1,179 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan anti-fake classifier
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/antifake/antifake.h"
+
+#include <limits.h>
+#include <stdint.h>
+
+int
+goodix_milan_antifake_model_score (
+ const int32_t vector[51],
+ int32_t *score)
+{
+ static const int32_t coefficients[3][51] = {
+ {
+ -881719, -58411, -460347, -335962, -47999, 29399, -186137,
+ 218335, -202819, 442778, 62551, 167207, 168755, 154635,
+ 799758, 219867, -212815, 94435, 185941, -156653, -86768,
+ 251010, 5761, -30002, 328469, 214185, -910040, -274539,
+ 154810, 93271, 484464, -43376, -124520, 301790, 493756,
+ 193732, 33331, 123407, -96289, -162522, 101447, -16494,
+ 24321, -60577, 399584, -130566, -103732, -152795, -154894,
+ -178784, 444620,
+ },
+ {
+ -866330, -168716, -630017, -594975, -156495, 70847, -54945,
+ 266503, 178411, 875699, 307277, 176863, 332214, 369364,
+ 898523, 169352, 3588, 266863, 404322, -535741, 74253, 273206,
+ 53473, 234738, 208033, 169163, -474512, -232840, 128840,
+ 116924, 502816, 229632, 237877, 399671, 535274, 440234,
+ 42991, -117560, -118880, -28531, 120452, 19973, 294438,
+ 95383, 563415, -49589, 4058, -166184, -177503, -85203, 555291,
+ },
+ {
+ -948340, -250213, -656204, -406007, -131997, -13883, -38493,
+ 250237, 122625, 662349, 89881, 83237, 161596, 395349, 747880,
+ 65116, -125278, 164230, 347575, -438777, 104650, 298676,
+ 107056, 212462, 116398, 65515, -501033, -197080, 130394, 99012,
+ 337049, 95841, 143597, 27112, 404840, 321412, 77898, -63774,
+ -110036, -33350, 115883, 207773, 338726, 191328, 459497,
+ -134510, -183482, -195391, -127574, 60763, 544563,
+ },
+ };
+ static const int32_t biases[3] = {
+ -66765, -5325, -51610,
+ };
+
+ if (!vector || !score)
+ return -1;
+
+ int32_t best = INT32_MAX;
+ for (size_t model = 0; model < 3; model++)
+ {
+ uint32_t dot = 0;
+
+ for (size_t i = 0; i < 51; i++)
+ dot += (uint32_t) vector[i] * (uint32_t) coefficients[model][i];
+ int32_t rounded = (int32_t) (dot + 0x800);
+ rounded >>= 12;
+ int32_t current = (int32_t) ((uint32_t) biases[model] -
+ (uint32_t) rounded);
+
+ if (current < best)
+ best = current;
+ }
+ *score = best;
+ return 0;
+}
+
+static int
+antifake_ring_class (const uint16_t *residual,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ size_t row,
+ size_t column,
+ size_t radius,
+ size_t border)
+{
+ static const int8_t ring_1[8][2] = {
+ { 1, 0 }, { 1, 1 }, { 0, 1 }, {-1, 1 },
+ {-1, 0 }, {-1,-1 }, { 0,-1 }, { 1,-1 },
+ };
+ static const int8_t ring_2[16][2] = {
+ { 2, 0 }, { 2, 1 }, { 1, 1 }, { 1, 2 },
+ { 0, 2 }, {-1, 2 }, {-1, 1 }, {-2, 1 },
+ {-2, 0 }, {-2,-1 }, {-1,-1 }, {-1,-2 },
+ { 0,-2 }, { 1,-2 }, { 1,-1 }, { 2,-1 },
+ };
+ static const int8_t ring_3[24][2] = {
+ { 3, 0 }, { 3, 1 }, { 3, 2 }, { 2, 2 },
+ { 2, 3 }, { 1, 3 }, { 0, 3 }, {-1, 3 },
+ {-2, 3 }, {-2, 2 }, {-3, 2 }, {-3, 1 },
+ {-3, 0 }, {-3,-1 }, {-3,-2 }, {-2,-2 },
+ {-2,-3 }, {-1,-3 }, { 0,-3 }, { 1,-3 },
+ { 2,-3 }, { 2,-2 }, { 3,-2 }, { 3,-1 },
+ };
+ uint8_t bits[24];
+ const int8_t (*ring)[2] = radius == 1 ? ring_1
+ : radius == 2 ? ring_2 : ring_3;
+ size_t bit_count = radius * 8;
+
+ if (row < radius + border || row + radius >= rows - border ||
+ column < radius + border || column + radius >= columns - border)
+ return -1;
+
+ uint16_t center = residual[row * columns + column];
+ for (size_t i = 0; i < bit_count; i++)
+ bits[i] = center <= residual[(size_t) ((ptrdiff_t) row + ring[i][1]) *
+ columns +
+ (size_t) ((ptrdiff_t) column + ring[i][0])];
+
+ size_t ones = 0;
+ size_t transitions = 0;
+ for (size_t i = 0; i < bit_count; i++)
+ {
+ size_t neighbor =
+ (size_t) ((ptrdiff_t) row + ring[i][1]) * columns +
+ (size_t) ((ptrdiff_t) column + ring[i][0]);
+ if (mask[neighbor] == 0)
+ return -1;
+ ones += bits[i];
+ if (i != 0 && bits[i] != bits[i - 1])
+ transitions++;
+ }
+ transitions += bits[0] != bits[bit_count - 1];
+ return transitions > 2 ? (int) bit_count + 1 : (int) ones;
+}
+
+int
+goodix_milan_antifake_model_vector (
+ const uint16_t *residual,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ size_t border,
+ int32_t vector[51])
+{
+ uint32_t counts[3][26] = { { 0 } };
+ const size_t bins[3] = { 10, 18, 26 };
+ size_t output = 0;
+
+ if (!residual || !mask || !vector || rows <= border * 2 ||
+ columns <= border * 2 || columns > SIZE_MAX / rows)
+ return -1;
+
+ for (size_t row = border; row < rows - border; row++)
+ for (size_t column = border; column < columns - border; column++)
+ for (size_t radius = 1; radius <= 3; radius++)
+ {
+ int classification = antifake_ring_class (
+ residual, mask, rows, columns, row, column, radius, border);
+
+ if (classification >= 0)
+ counts[radius - 1][classification]++;
+ }
+
+ for (size_t radius = 0; radius < 3; radius++)
+ {
+ uint32_t total = 0;
+
+ for (size_t i = 0; i < bins[radius]; i++)
+ total += counts[radius][i];
+ for (size_t i = 0; i + 1 < bins[radius]; i++)
+ vector[output++] = total == 0
+ ? (int32_t) (counts[radius][i] << 12)
+ : (int32_t) ((counts[radius][i] * 0x1000 +
+ total / 2) /
+ total);
+ }
+ return 0;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/antifake/construction.c b/libfprint/drivers/goodix53x5/milan/antifake/construction.c
new file mode 100644
index 0000000..34f3893
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/antifake/construction.c
@@ -0,0 +1,392 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan anti-fake construction
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/antifake/antifake.h"
+#include "milan/print.h"
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int milan_antifake_collect_candidates (
+ GoodixMilanAntifakeBlob *antifake,
+ size_t antifake_size,
+ const uint16_t *source,
+ size_t rows,
+ size_t columns,
+ int32_t x_adjustment);
+
+static int milan_antifake_build_class (
+ const uint16_t *calibration,
+ const uint16_t *raw_frame,
+ const uint8_t *classification_plane,
+ const uint8_t *feature_mask,
+ size_t feature_mask_size,
+ size_t rows,
+ size_t columns,
+ uint16_t t_code,
+ uint16_t dac_high,
+ uint16_t dac_low,
+ uint16_t chip_type,
+ int32_t calibration_scalar,
+ GoodixMilanAntifakeBlob *antifake,
+ size_t antifake_size);
+
+static int32_t
+milan_antifake_sensor_offset (uint16_t t_code,
+ uint16_t dac_high,
+ uint16_t dac_low,
+ uint16_t chip_type)
+{
+ uint32_t difference = (uint32_t) dac_high - dac_low;
+ uint32_t scale = 0x11b;
+
+ if (chip_type == 0x11)
+ {
+ difference += 0x55;
+ scale = 0x146;
+ }
+
+ return (int32_t) (difference * t_code * scale) / 1000;
+}
+
+int
+goodix_milan_antifake_build (
+ const uint16_t *calibration,
+ const uint16_t *raw_frame,
+ const uint8_t *classification_plane,
+ const uint8_t *feature_mask,
+ size_t feature_mask_size,
+ size_t rows,
+ size_t columns,
+ uint16_t t_code,
+ uint16_t dac_high,
+ uint16_t dac_low,
+ uint16_t chip_type,
+ int32_t calibration_scalar,
+ GoodixMilanAntifakeBlob *antifake,
+ size_t antifake_size)
+{
+ return milan_antifake_build_class (
+ calibration, raw_frame, classification_plane, feature_mask,
+ feature_mask_size, rows, columns, t_code, dac_high, dac_low, chip_type,
+ calibration_scalar, antifake, antifake_size);
+}
+
+static int
+milan_antifake_build_class (
+ const uint16_t *calibration,
+ const uint16_t *raw_frame,
+ const uint8_t *classification_plane,
+ const uint8_t *feature_mask,
+ size_t feature_mask_size,
+ size_t rows,
+ size_t columns,
+ uint16_t t_code,
+ uint16_t dac_high,
+ uint16_t dac_low,
+ uint16_t chip_type,
+ int32_t calibration_scalar,
+ GoodixMilanAntifakeBlob *antifake,
+ size_t antifake_size)
+{
+ uint16_t *residual = NULL;
+ uint8_t *mask = NULL;
+ uint8_t *classes = NULL;
+ int32_t vector[51];
+ int32_t threshold;
+ int32_t texture;
+ int32_t mean;
+ int32_t variation;
+ int32_t boundary;
+ int32_t model;
+ size_t count;
+ int result = -1;
+
+ if (!calibration || !raw_frame || !classification_plane || !feature_mask ||
+ !antifake || antifake_size < GOODIX_MILAN_ANTIFAKE_SIZE || rows < 2 ||
+ columns <= 4 ||
+ columns > SIZE_MAX / rows)
+ return -1;
+ count = rows * columns;
+ if (count > SIZE_MAX / sizeof(*residual))
+ return -1;
+ residual = malloc (count * sizeof(*residual));
+ mask = malloc (count);
+ classes = malloc (count);
+ if (!residual || !mask || !classes)
+ goto out;
+
+ memset (goodix_milan_antifake_data (antifake), 0, sizeof(*antifake));
+ if (goodix_milan_antifake_residual (
+ calibration, raw_frame, rows, columns,
+ milan_antifake_sensor_offset (t_code, dac_high, dac_low, chip_type),
+ chip_type, residual) != 0 ||
+ goodix_milan_antifake_build_mask (
+ feature_mask, feature_mask_size, rows, columns, mask,
+ goodix_milan_antifake_mask (antifake),
+ GOODIX_MILAN_ANTIFAKE_MASK_SIZE) != 0 ||
+ goodix_milan_antifake_impulse_filter (
+ residual, rows, columns, &threshold) != 0)
+ goto out;
+ goodix_milan_antifake_set_calibration_scalar (antifake,
+ calibration_scalar);
+ goodix_milan_antifake_set_threshold (antifake, threshold);
+
+ if (milan_antifake_collect_candidates (
+ antifake, antifake_size, residual, rows, columns,
+ chip_type == GOODIX_MILAN_PRINT_SENSOR_TYPE ? 0 : -2) != 0)
+ goto out;
+
+ if (goodix_milan_antifake_statistics (
+ residual, mask, rows, columns, &texture, &mean) != 0 ||
+ goodix_milan_antifake_block_variation (
+ residual, mask, rows, columns, 12, &variation) != 0 ||
+ goodix_milan_antifake_class_map (
+ classification_plane, mask, rows, columns, classes) != 0 ||
+ goodix_milan_antifake_boundary_score (
+ residual, classes, rows, columns, &boundary) != 0 ||
+ goodix_milan_antifake_model_vector (
+ residual, mask, rows, columns, 2, vector) != 0 ||
+ goodix_milan_antifake_model_score (vector, &model) != 0)
+ goto out;
+ goodix_milan_antifake_set_texture (antifake, texture);
+ goodix_milan_antifake_set_mean (antifake, mean);
+ goodix_milan_antifake_set_variation (antifake, variation);
+ goodix_milan_antifake_set_boundary (antifake, boundary);
+ goodix_milan_antifake_set_model (antifake, model);
+
+ if (chip_type == GOODIX_MILAN_PRINT_SENSOR_TYPE)
+ {
+ if (columns != 0 && rows > SIZE_MAX / columns)
+ goto out;
+ size_t packed_pixels = rows * columns;
+ uint8_t *packed_mask = goodix_milan_antifake_mask (antifake);
+
+ if (packed_pixels > GOODIX_MILAN_ANTIFAKE_MASK_SIZE * 8)
+ goto out;
+
+ memset (packed_mask, 0, GOODIX_MILAN_ANTIFAKE_MASK_SIZE);
+ for (size_t i = 0; i < packed_pixels; i++)
+ if (mask[i] != 0)
+ packed_mask[i / 8] |= (uint8_t) (1U << (i & 7));
+ }
+ if (columns <= 4 ||
+ goodix_milan_antifake_feature_update (
+ antifake, antifake_size, residual, rows, columns - 4) != 0)
+ goto out;
+ result = 0;
+
+out:
+ free (classes);
+ free (mask);
+ free (residual);
+ return result;
+}
+
+int
+goodix_milan_antifake_build_with_boundary (
+ const uint16_t *calibration,
+ const uint16_t *raw_frame,
+ const uint8_t *classification_plane,
+ const uint8_t *feature_mask,
+ size_t feature_mask_size,
+ size_t rows,
+ size_t columns,
+ uint16_t t_code,
+ uint16_t dac_high,
+ uint16_t dac_low,
+ uint16_t chip_type,
+ int32_t calibration_scalar,
+ GoodixMilanAntifakeBlob *antifake,
+ size_t antifake_size,
+ GoodixMilanAntifakeBoundaryResult *boundary_result)
+{
+ GoodixMilanAntifakeBlob *alternate_antifake = NULL;
+ uint8_t *alternate_feature_mask = NULL;
+ int result;
+
+ if (boundary_result)
+ memset (boundary_result, 0, sizeof(*boundary_result));
+ result = milan_antifake_build_class (
+ calibration, raw_frame, classification_plane, feature_mask,
+ feature_mask_size, rows, columns, t_code, dac_high, dac_low, chip_type,
+ calibration_scalar, antifake, antifake_size);
+ if (result != 0 || chip_type != GOODIX_MILAN_PRINT_SENSOR_TYPE ||
+ rows != GOODIX_MILAN_SENSOR_ROWS ||
+ columns != GOODIX_MILAN_SENSOR_COLUMNS ||
+ feature_mask_size != 52 * 44)
+ return result;
+
+ alternate_antifake = malloc (sizeof(*alternate_antifake));
+ alternate_feature_mask = malloc (feature_mask_size + 1);
+ if (!alternate_antifake || !alternate_feature_mask)
+ {
+ result = -1;
+ goto out;
+ }
+ memcpy (alternate_feature_mask, feature_mask, feature_mask_size);
+ alternate_feature_mask[feature_mask_size] = 1;
+ result = milan_antifake_build_class (
+ calibration, raw_frame, classification_plane, alternate_feature_mask,
+ feature_mask_size + 1, rows, columns, t_code, dac_high, dac_low, chip_type,
+ calibration_scalar, alternate_antifake,
+ GOODIX_MILAN_ANTIFAKE_DEFINED_MATERIAL_SIZE);
+ if (result != 0)
+ goto out;
+
+ if (boundary_result)
+ {
+ memcpy (&boundary_result->zero_projection, antifake, sizeof(*antifake));
+ memcpy (&boundary_result->nonzero_projection, alternate_antifake,
+ sizeof(*alternate_antifake));
+ boundary_result->zero_candidate_count =
+ goodix_milan_antifake_candidate_count (antifake);
+ boundary_result->nonzero_candidate_count =
+ goodix_milan_antifake_candidate_count (alternate_antifake);
+ }
+ if (memcmp (goodix_milan_antifake_const_data (antifake),
+ goodix_milan_antifake_const_data (alternate_antifake),
+ sizeof(*antifake)) != 0)
+ {
+ if (boundary_result)
+ boundary_result->classification =
+ GOODIX_MILAN_ANTIFAKE_BOUNDARY_AMBIGUOUS;
+ result = GOODIX_MILAN_ANTIFAKE_AMBIGUOUS;
+ goto out;
+ }
+ if (boundary_result)
+ boundary_result->classification = GOODIX_MILAN_ANTIFAKE_BOUNDARY_STABLE;
+
+out:
+ free (alternate_feature_mask);
+ free (alternate_antifake);
+ return result;
+}
+
+static int
+milan_antifake_collect_candidates (
+ GoodixMilanAntifakeBlob *antifake,
+ size_t antifake_size,
+ const uint16_t *source,
+ size_t rows,
+ size_t columns,
+ int32_t x_adjustment)
+{
+ static const int8_t offsets[44][2] = {
+ { 1, 0 }, { 1, 1 }, { 0, 1 }, {-1, 1 }, {-1, 0 }, {-1,-1 },
+ { 0,-1 }, { 1,-1 }, { 2, 0 }, { 2, 1 }, { 1, 2 }, { 0, 2 },
+ {-1, 2 }, {-2, 1 }, {-2, 0 }, {-2,-1 }, {-1,-2 }, { 0,-2 },
+ { 1,-2 }, { 2,-1 }, { 3, 0 }, { 3, 1 }, { 3, 2 }, { 2, 2 },
+ { 2, 3 }, { 1, 3 }, { 0, 3 }, {-1, 3 }, {-2, 3 }, {-2, 2 },
+ {-3, 2 }, {-3, 1 }, {-3, 0 }, {-3,-1 }, {-3,-2 }, {-2,-2 },
+ {-2,-3 }, {-1,-3 }, { 0,-3 }, { 1,-3 }, { 2,-3 }, { 2,-2 },
+ { 3,-2 }, { 3,-1 },
+ };
+ typedef struct
+ {
+ int32_t x;
+ int32_t y;
+ int32_t metric;
+ int invalid;
+ } AntifakeCandidate;
+ AntifakeCandidate candidates[400];
+ size_t candidate_count = 0;
+ uint32_t output_count = 0;
+
+ if (!antifake || !source || antifake_size < GOODIX_MILAN_ANTIFAKE_SIZE ||
+ rows <= 8 ||
+ columns <= 8 || columns > SIZE_MAX / rows)
+ return -1;
+ const uint8_t *mask = goodix_milan_antifake_const_mask (antifake);
+ size_t cropped_columns = columns - 4;
+ for (size_t y = 4; y + 4 < rows; y++)
+ for (size_t x = 4; x + 4 < columns; x++)
+ {
+ size_t pixel = y * columns + x;
+ uint16_t center = source[pixel];
+ int32_t metric = 0;
+ size_t mask_bit = y * cropped_columns + x - 2;
+ int accepted =
+ (mask[mask_bit >> 3] & (1U << (mask_bit & 7))) != 0;
+
+ if (!accepted)
+ continue;
+ for (size_t i = 0; i < 44; i++)
+ {
+ uint16_t neighbor = source[(size_t) ((ptrdiff_t) y + offsets[i][1]) *
+ columns +
+ (size_t) ((ptrdiff_t) x + offsets[i][0])];
+
+ if (center < neighbor)
+ {
+ accepted = 0;
+ break;
+ }
+ metric += center - neighbor;
+ }
+ if (accepted && candidate_count < 400)
+ candidates[candidate_count++] = (AntifakeCandidate) {
+ (int32_t) x, (int32_t) y, metric, 0,
+ };
+ }
+ for (size_t i = 0; i < candidate_count; i++)
+ {
+ if (candidates[i].invalid)
+ continue;
+ for (size_t j = i + 1; j < candidate_count; j++)
+ {
+ if (candidates[j].invalid)
+ continue;
+ int32_t delta_x = candidates[i].x - candidates[j].x;
+ int32_t delta_y = candidates[i].y - candidates[j].y;
+
+ if (abs (delta_x) <= 3 && abs (delta_y) <= 3 &&
+ delta_x * delta_x + delta_y * delta_y < 10)
+ {
+ if (candidates[j].metric < candidates[i].metric)
+ {
+ candidates[i].invalid = 1;
+ break;
+ }
+ candidates[j].invalid = 1;
+ }
+ }
+ }
+ memset (goodix_milan_antifake_data (antifake), 0,
+ GOODIX_MILAN_ANTIFAKE_RECORDS_SIZE);
+ for (size_t i = 0;
+ i < candidate_count &&
+ output_count < GOODIX_MILAN_ANTIFAKE_RECORD_CAPACITY;
+ i++)
+ if (!candidates[i].invalid)
+ {
+ uint8_t *record = goodix_milan_antifake_record (antifake,
+ output_count);
+
+ goodix_milan_antifake_set_record_x (record, candidates[i].x);
+ goodix_milan_antifake_set_record_y (record, candidates[i].y);
+ memcpy (record + GOODIX_MILAN_ANTIFAKE_RECORD_DATA_24_OFFSET,
+ &candidates[i].metric,
+ sizeof(candidates[i].metric));
+ output_count++;
+ }
+ for (size_t i = 0; i < output_count; i++)
+ {
+ int32_t x;
+ uint8_t *record = goodix_milan_antifake_record (antifake, i);
+
+ x = goodix_milan_antifake_record_x (record);
+ x += x_adjustment;
+ goodix_milan_antifake_set_record_x (record, x);
+ }
+ goodix_milan_antifake_set_candidate_count (antifake, output_count);
+ return 0;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/antifake/feature.c b/libfprint/drivers/goodix53x5/milan/antifake/feature.c
new file mode 100644
index 0000000..0002d0e
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/antifake/feature.c
@@ -0,0 +1,169 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan anti-fake feature records
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/antifake/antifake.h"
+#include "milan/feature/feature.h"
+#include "milan/private.h"
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+int
+goodix_milan_antifake_feature_maps (
+ const uint16_t *source,
+ size_t rows,
+ size_t columns,
+ uint8_t *dense_orientation,
+ uint32_t *magnitude,
+ int16_t *gradient_orientation)
+{
+ size_t count;
+ uint8_t *frame = NULL;
+ int result = -1;
+
+ if (!source || !dense_orientation || !magnitude || !gradient_orientation ||
+ rows < 2 || columns < 2 || columns > SIZE_MAX / rows)
+ return -1;
+ count = rows * columns;
+ frame = malloc (count);
+ if (!frame)
+ goto out;
+ for (size_t i = 0; i < count; i++)
+ {
+ uint32_t value = source[i] / 12;
+
+ frame[i] = (uint8_t) (value > UINT8_MAX ? UINT8_MAX : value);
+ }
+ if (feature_build_dense_orientation (
+ frame, rows, columns, 7, dense_orientation) != 0)
+ goto out;
+ memset (magnitude, 0, count * sizeof(*magnitude));
+ memset (gradient_orientation, 0,
+ count * sizeof(*gradient_orientation));
+ for (size_t row = 1; row + 1 < rows; row++)
+ for (size_t column = 1; column + 1 < columns; column++)
+ {
+ size_t i = row * columns + column;
+ int32_t horizontal =
+ ((int32_t) frame[i + 1] - frame[i - 1]) * 0x100;
+ int32_t vertical =
+ ((int32_t) frame[i + columns] - frame[i - columns]) * 0x100;
+
+ horizontal *= 0x1000;
+ vertical *= 0x1000;
+ gradient_orientation[i] =
+ (int16_t) feature_cordic (vertical, &horizontal);
+ magnitude[i] = (uint32_t) (horizontal >> 12);
+ if (magnitude[i] > 0x3ffff)
+ magnitude[i] = 0x3ffff;
+ }
+ result = 0;
+
+out:
+ free (frame);
+ return result;
+}
+
+int
+goodix_milan_antifake_feature_record (
+ const uint8_t *dense_orientation,
+ const uint32_t *magnitude,
+ const int16_t *gradient_orientation,
+ size_t rows,
+ size_t columns,
+ int32_t x,
+ int32_t y,
+ GoodixMilanFeatureRecord *record)
+{
+ GoodixMilanFeatureAux auxiliary = { 0 };
+
+ if (!dense_orientation || !magnitude || !gradient_orientation || !record ||
+ x < 0 || y < 0 || (size_t) x >= columns || (size_t) y >= rows)
+ return -1;
+ int32_t degrees = (270 - dense_orientation[(size_t) y * columns +
+ (size_t) x]) % 180;
+ memset (record, 0, sizeof(*record));
+ record->refined_x = (int16_t) (x << 8);
+ record->refined_y = (int16_t) (y << 8);
+ record->orientation = (int16_t) ((degrees * 0x6488) / 360);
+ auxiliary.x = x;
+ auxiliary.y = y;
+ feature_build_descriptor (magnitude, gradient_orientation, rows, columns,
+ 0xc117, &auxiliary, record);
+ return 0;
+}
+
+int
+goodix_milan_antifake_feature_update (
+ GoodixMilanAntifakeBlob *antifake,
+ size_t antifake_size,
+ const uint16_t *source,
+ size_t rows,
+ size_t columns)
+{
+ size_t count;
+ uint8_t *dense_orientation = NULL;
+ uint32_t *magnitude = NULL;
+ int16_t *gradient_orientation = NULL;
+ uint32_t record_count;
+ int result = -1;
+
+ if (!antifake || !source ||
+ antifake_size < GOODIX_MILAN_ANTIFAKE_SIZE || rows < 2 || columns < 2 ||
+ columns > SIZE_MAX / rows)
+ return -1;
+ count = rows * columns;
+ record_count = goodix_milan_antifake_candidate_count (antifake);
+ if (record_count > GOODIX_MILAN_ANTIFAKE_RECORD_CAPACITY ||
+ record_count * GOODIX_MILAN_ANTIFAKE_RECORD_SIZE >
+ GOODIX_MILAN_ANTIFAKE_RECORDS_SIZE)
+ return -1;
+
+ dense_orientation = malloc (count);
+ magnitude = malloc (count * sizeof(*magnitude));
+ gradient_orientation = malloc (count * sizeof(*gradient_orientation));
+ if (!dense_orientation || !magnitude || !gradient_orientation)
+ goto out;
+ if (goodix_milan_antifake_feature_maps (
+ source, rows, columns, dense_orientation, magnitude,
+ gradient_orientation) != 0)
+ goto out;
+
+ for (size_t i = 0; i < record_count; i++)
+ {
+ uint8_t *target = goodix_milan_antifake_record (antifake, i);
+ int32_t x;
+ int32_t y;
+ GoodixMilanFeatureRecord record = { 0 };
+
+ x = goodix_milan_antifake_record_x (target);
+ y = goodix_milan_antifake_record_y (target);
+ if (goodix_milan_antifake_feature_record (
+ dense_orientation, magnitude, gradient_orientation, rows, columns,
+ x, y, &record) != 0)
+ goto out;
+ goodix_milan_feature_transform_record ((uint8_t *) &record, 1);
+ memcpy (target + GOODIX_MILAN_ANTIFAKE_RECORD_DATA_8_OFFSET,
+ (uint8_t *) &record + 40, 16);
+ memcpy (target + GOODIX_MILAN_ANTIFAKE_RECORD_DATA_24_OFFSET,
+ (uint8_t *) &record + 16, 16);
+ memcpy (target + GOODIX_MILAN_ANTIFAKE_RECORD_DATA_40_OFFSET,
+ (uint8_t *) &record + 32, 8);
+ }
+ goodix_milan_antifake_set_pair_score (antifake, -1);
+ result = 0;
+
+out:
+ free (gradient_orientation);
+ free (magnitude);
+ free (dense_orientation);
+ return result;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/antifake/mask.c b/libfprint/drivers/goodix53x5/milan/antifake/mask.c
new file mode 100644
index 0000000..243866d
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/antifake/mask.c
@@ -0,0 +1,131 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan anti-fake mask
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/antifake/antifake.h"
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+static void
+antifake_mask_dilate (const uint8_t *source,
+ uint8_t *output,
+ size_t rows,
+ size_t columns)
+{
+ for (size_t y = 0; y < rows; y++)
+ for (size_t x = 0; x < columns; x++)
+ {
+ size_t i = y * columns + x;
+ int active = source[i] != 0 ||
+ (x >= 1 && source[i - 1] != 0) ||
+ (x + 1 < columns && source[i + 1] != 0) ||
+ (y >= 1 && source[i - columns] != 0) ||
+ (y + 1 < rows && source[i + columns] != 0) ||
+ (x >= 2 && source[i - 2] != 0) ||
+ (x + 2 < columns && source[i + 2] != 0) ||
+ (y >= 2 && source[i - columns * 2] != 0) ||
+ (y + 2 < rows && source[i + columns * 2] != 0);
+
+ output[i] = active ? UINT8_MAX : 0;
+ }
+}
+
+static void
+antifake_mask_erode (const uint8_t *source,
+ uint8_t *output,
+ size_t rows,
+ size_t columns)
+{
+ for (size_t y = 0; y < rows; y++)
+ for (size_t x = 0; x < columns; x++)
+ {
+ size_t i = y * columns + x;
+ int inactive = source[i] == 0 ||
+ (x >= 1 && source[i - 1] == 0) ||
+ (x + 1 < columns && source[i + 1] == 0) ||
+ (y >= 1 && source[i - columns] == 0) ||
+ (y + 1 < rows && source[i + columns] == 0) ||
+ (x >= 2 && source[i - 2] == 0) ||
+ (x + 2 < columns && source[i + 2] == 0) ||
+ (y >= 2 && source[i - columns * 2] == 0) ||
+ (y + 2 < rows && source[i + columns * 2] == 0);
+
+ output[i] = inactive ? 0 : UINT8_MAX;
+ }
+}
+
+int
+goodix_milan_antifake_build_mask (
+ const uint8_t *feature_mask,
+ size_t feature_mask_size,
+ size_t rows,
+ size_t columns,
+ uint8_t *mask,
+ uint8_t *packed,
+ size_t packed_size)
+{
+ size_t count;
+ size_t cropped_columns;
+ size_t last_feature_row;
+ size_t last_feature_column;
+ size_t maximum_feature_index;
+ uint8_t *temporary = NULL;
+
+ if (!feature_mask || !mask || !packed || rows < 2 || columns <= 4 ||
+ columns > SIZE_MAX / rows || feature_mask_size == 0)
+ return -1;
+ count = rows * columns;
+ cropped_columns = columns - 4;
+ last_feature_row = (rows - 1) / 2;
+ last_feature_column = (columns - 3) / 2;
+ if (last_feature_row > (SIZE_MAX - last_feature_column) / 52)
+ return -1;
+ maximum_feature_index = last_feature_row * 52 + last_feature_column;
+ if (rows > SIZE_MAX / cropped_columns ||
+ feature_mask_size < maximum_feature_index ||
+ packed_size < (rows * cropped_columns + 7) / 8)
+ return -1;
+ temporary = malloc (count);
+ if (!temporary)
+ return -1;
+ memset (mask, 0, count);
+ for (size_t y = 0; y < rows; y++)
+ for (size_t x = 2; x + 2 < columns; x++)
+ {
+ size_t feature_index = (y / 2) * 52 + x / 2;
+
+ /* Windows reads data[2288] for the lower-right 2x2 of this exact
+ * profile-9 matrix. canonical-zero-v1 defines that one UB source as
+ * inactive; every in-range byte remains authoritative. */
+ if (feature_index < feature_mask_size
+ ? feature_mask[feature_index] != 0
+ : 0)
+ mask[y * columns + x] = 1;
+ }
+ antifake_mask_dilate (mask, temporary, rows, columns);
+ antifake_mask_erode (temporary, mask, rows, columns);
+ antifake_mask_erode (mask, temporary, rows, columns);
+ antifake_mask_erode (temporary, mask, rows, columns);
+ antifake_mask_erode (mask, temporary, rows, columns);
+ memcpy (mask, temporary, count);
+
+ memset (packed, 0, packed_size);
+ for (size_t y = 0; y < rows; y++)
+ for (size_t x = 2; x + 2 < columns; x++)
+ {
+ size_t bit = y * cropped_columns + x - 2;
+
+ if (mask[y * columns + x] != 0)
+ packed[bit >> 3] |= (uint8_t) (1U << (bit & 7));
+ }
+ free (temporary);
+ return 0;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/antifake/morphology.c b/libfprint/drivers/goodix53x5/milan/antifake/morphology.c
new file mode 100644
index 0000000..ddf91ec
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/antifake/morphology.c
@@ -0,0 +1,489 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan anti-fake morphology
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+/*
+ * Anti-fake boundary score: a threshold class map completed by a
+ * priority-flood watershed (native FUN_18003d1a0, FUN_18003c680), Zhang-Suen
+ * thinning of the DARK class (FUN_18003b6d0), and a rounded ratio of residual
+ * differences along the skeleton (FUN_18003ad10). Contracts are in
+ * re/milan/functions on milan-dev; "Native quirk" comments mark behaviour that
+ * must not be corrected.
+ */
+
+#include "milan/antifake/antifake.h"
+#include "milan/transform-private.h"
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* Label values are native; the watershed treats every nonzero label, including
+ * QUEUED, EXCLUDED, and CONFLICT, as an assigned neighbour. */
+#define ANTIFAKE_CLASS_UNASSIGNED 0x00
+#define ANTIFAKE_CLASS_BRIGHT 0x01
+#define ANTIFAKE_CLASS_DARK 0x02
+#define ANTIFAKE_CLASS_QUEUED 0xfd
+#define ANTIFAKE_CLASS_EXCLUDED 0xfe
+#define ANTIFAKE_CLASS_CONFLICT 0xff
+
+#define ANTIFAKE_DARK_BELOW 0x1a
+#define ANTIFAKE_BRIGHT_FROM 0xe7
+
+/* One level per absolute 8-bit intensity difference. */
+#define WATERSHED_PRIORITY_LEVELS 256
+
+#define THINNING_MAX_ITERATIONS 100
+#define BOUNDARY_SCORE_SCALE 1000
+
+/* Visit order (left, right, up, down) decides label ties and queue order. */
+static const int8_t four_neighbor_dx[4] = {-1, 1, 0, 0};
+static const int8_t four_neighbor_dy[4] = { 0, 0, -1, 1};
+
+static inline size_t
+four_neighbor_index (size_t row,
+ size_t column,
+ size_t columns,
+ size_t direction)
+{
+ return (size_t) ((ptrdiff_t) row + four_neighbor_dy[direction]) * columns +
+ (size_t) ((ptrdiff_t) column + four_neighbor_dx[direction]);
+}
+
+static inline int
+absolute_difference (uint8_t first,
+ uint8_t second)
+{
+ int difference = (int) first - second;
+
+ return difference < 0 ? -difference : difference;
+}
+
+/* Pixels pop from the lowest nonempty level, LIFO within a level; both
+ * properties determine the class map. `next` is indexed by pixel. */
+typedef struct
+{
+ int32_t heads[WATERSHED_PRIORITY_LEVELS];
+ int32_t *next;
+ int current_priority;
+} WatershedQueue;
+
+static int
+watershed_queue_init (WatershedQueue *queue,
+ size_t count)
+{
+ queue->next = malloc (count * sizeof (*queue->next));
+ if (!queue->next)
+ return -1;
+ for (size_t i = 0; i < WATERSHED_PRIORITY_LEVELS; i++)
+ queue->heads[i] = -1;
+ for (size_t i = 0; i < count; i++)
+ queue->next[i] = -1;
+ queue->current_priority = 0;
+ return 0;
+}
+
+static void
+watershed_queue_free (WatershedQueue *queue)
+{
+ free (queue->next);
+ queue->next = NULL;
+}
+
+static void
+watershed_queue_push (WatershedQueue *queue,
+ size_t pixel,
+ int priority)
+{
+ queue->next[pixel] = queue->heads[priority];
+ queue->heads[priority] = (int32_t) pixel;
+ if (priority < queue->current_priority)
+ queue->current_priority = priority;
+}
+
+static int32_t
+watershed_queue_pop (WatershedQueue *queue)
+{
+ int32_t pixel;
+
+ while (queue->current_priority < WATERSHED_PRIORITY_LEVELS &&
+ queue->heads[queue->current_priority] == -1)
+ queue->current_priority++;
+ if (queue->current_priority >= WATERSHED_PRIORITY_LEVELS)
+ return -1;
+ pixel = queue->heads[queue->current_priority];
+ queue->heads[queue->current_priority] = queue->next[pixel];
+ queue->next[pixel] = -1;
+ return pixel;
+}
+
+static void
+classify_by_intensity (const uint8_t *image,
+ const uint8_t *mask,
+ size_t count,
+ uint8_t *classes)
+{
+ for (size_t i = 0; i < count; i++)
+ {
+ if (image[i] >= ANTIFAKE_BRIGHT_FROM)
+ classes[i] = ANTIFAKE_CLASS_BRIGHT;
+ else if (image[i] < ANTIFAKE_DARK_BELOW)
+ classes[i] = ANTIFAKE_CLASS_DARK;
+ else
+ classes[i] = ANTIFAKE_CLASS_UNASSIGNED;
+ if (mask[i] == 0)
+ classes[i] = ANTIFAKE_CLASS_EXCLUDED;
+ }
+}
+
+static void
+exclude_border (uint8_t *classes,
+ size_t rows,
+ size_t columns)
+{
+ memset (classes, ANTIFAKE_CLASS_EXCLUDED, columns);
+ memset (classes + (rows - 1) * columns, ANTIFAKE_CLASS_EXCLUDED, columns);
+ for (size_t row = 1; row + 1 < rows; row++)
+ {
+ classes[row * columns] = ANTIFAKE_CLASS_EXCLUDED;
+ classes[row * columns + columns - 1] = ANTIFAKE_CLASS_EXCLUDED;
+ }
+}
+
+static void
+watershed_seed (const uint8_t *image,
+ uint8_t *classes,
+ size_t rows,
+ size_t columns,
+ WatershedQueue *queue)
+{
+ for (size_t row = 1; row + 1 < rows; row++)
+ for (size_t column = 1; column + 1 < columns; column++)
+ {
+ size_t pixel = row * columns + column;
+ int priority = WATERSHED_PRIORITY_LEVELS;
+
+ if (classes[pixel] != ANTIFAKE_CLASS_UNASSIGNED)
+ continue;
+ for (size_t direction = 0; direction < 4; direction++)
+ {
+ size_t neighbor = four_neighbor_index (row, column, columns,
+ direction);
+
+ if (classes[neighbor] == ANTIFAKE_CLASS_UNASSIGNED)
+ continue;
+ int difference = absolute_difference (image[pixel],
+ image[neighbor]);
+ if (difference < priority)
+ priority = difference;
+ }
+ if (priority < WATERSHED_PRIORITY_LEVELS)
+ {
+ watershed_queue_push (queue, pixel, priority);
+ classes[pixel] = ANTIFAKE_CLASS_QUEUED;
+ }
+ }
+}
+
+/* Native quirk: QUEUED, EXCLUDED, and CONFLICT neighbours take part in
+ * inheritance like any other nonzero label. */
+static uint8_t
+watershed_inherit_label (const uint8_t *classes,
+ size_t row,
+ size_t column,
+ size_t columns)
+{
+ uint8_t label = ANTIFAKE_CLASS_UNASSIGNED;
+
+ for (size_t direction = 0; direction < 4; direction++)
+ {
+ uint8_t neighbor_label =
+ classes[four_neighbor_index (row, column, columns, direction)];
+
+ if (neighbor_label == ANTIFAKE_CLASS_UNASSIGNED)
+ continue;
+ if (label != ANTIFAKE_CLASS_UNASSIGNED && label != neighbor_label)
+ label = ANTIFAKE_CLASS_CONFLICT;
+ else
+ label = neighbor_label;
+ }
+ return label;
+}
+
+static void
+watershed_propagate (const uint8_t *image,
+ uint8_t *classes,
+ size_t columns,
+ WatershedQueue *queue)
+{
+ int32_t popped;
+
+ while ((popped = watershed_queue_pop (queue)) >= 0)
+ {
+ size_t pixel = (size_t) popped;
+ size_t row = pixel / columns;
+ size_t column = pixel % columns;
+ uint8_t label = watershed_inherit_label (classes, row, column, columns);
+
+ if (label != ANTIFAKE_CLASS_UNASSIGNED)
+ classes[pixel] = label;
+ if (label == ANTIFAKE_CLASS_CONFLICT)
+ continue;
+ for (size_t direction = 0; direction < 4; direction++)
+ {
+ size_t neighbor = four_neighbor_index (row, column, columns,
+ direction);
+
+ if (classes[neighbor] != ANTIFAKE_CLASS_UNASSIGNED)
+ continue;
+ watershed_queue_push (queue, neighbor,
+ absolute_difference (image[pixel],
+ image[neighbor]));
+ classes[neighbor] = ANTIFAKE_CLASS_QUEUED;
+ }
+ }
+}
+
+int
+goodix_milan_antifake_class_map (
+ const uint8_t *image,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ uint8_t *classes)
+{
+ WatershedQueue queue;
+ size_t count;
+
+ if (!image || !mask || !classes || rows < 2 || columns < 2 ||
+ columns > SIZE_MAX / rows)
+ return -1;
+ count = rows * columns;
+ if (watershed_queue_init (&queue, count) != 0)
+ return -1;
+
+ classify_by_intensity (image, mask, count, classes);
+ exclude_border (classes, rows, columns);
+ watershed_seed (image, classes, rows, columns, &queue);
+ watershed_propagate (image, classes, columns, &queue);
+
+ watershed_queue_free (&queue);
+ return 0;
+}
+
+/* Ring is clockwise from north. */
+static int
+zhang_suen_should_delete (const uint8_t *pixels,
+ size_t columns,
+ size_t pixel,
+ int second_subpass)
+{
+ const size_t ring[8] = {
+ pixel - columns, pixel - columns + 1, pixel + 1,
+ pixel + columns + 1, pixel + columns, pixel + columns - 1,
+ pixel - 1, pixel - columns - 1,
+ };
+ int population = 0;
+ int transitions = 0;
+
+ for (size_t i = 0; i < 8; i++)
+ {
+ int current = pixels[ring[i]] != 0;
+ int following = pixels[ring[(i + 1) % 8]] != 0;
+
+ population += current;
+ transitions += !current && following;
+ }
+ if (population < 2 || population > 6 || transitions != 1)
+ return 0;
+
+ int north = pixels[ring[0]] != 0;
+ int east = pixels[ring[2]] != 0;
+ int south = pixels[ring[4]] != 0;
+ int west = pixels[ring[6]] != 0;
+
+ return second_subpass ?
+ !(north && east && west) && !(north && south && west) :
+ !(north && east && south) && !(east && south && west);
+}
+
+static int
+zhang_suen_subpass (uint8_t *pixels,
+ const uint8_t *snapshot,
+ size_t rows,
+ size_t columns,
+ int second_subpass)
+{
+ int changed = 0;
+
+ for (size_t row = 1; row + 1 < rows; row++)
+ for (size_t column = 1; column + 1 < columns; column++)
+ {
+ size_t pixel = row * columns + column;
+
+ if (snapshot[pixel] != 0 &&
+ zhang_suen_should_delete (snapshot, columns, pixel,
+ second_subpass))
+ {
+ pixels[pixel] = 0;
+ changed = 1;
+ }
+ }
+ return changed;
+}
+
+/* Native quirk: convergence is tested on the second subpass only. */
+static int
+zhang_suen_thin (uint8_t *pixels,
+ size_t rows,
+ size_t columns,
+ size_t maximum_iterations)
+{
+ size_t count = rows * columns;
+ uint8_t *snapshot = malloc (count);
+
+ if (!snapshot)
+ return -1;
+ for (size_t iteration = 0; iteration < maximum_iterations; iteration++)
+ {
+ memcpy (snapshot, pixels, count);
+ zhang_suen_subpass (pixels, snapshot, rows, columns, 0);
+ memcpy (snapshot, pixels, count);
+ if (!zhang_suen_subpass (pixels, snapshot, rows, columns, 1))
+ break;
+ }
+ free (snapshot);
+ return 0;
+}
+
+/* Native quirk: the row and column margins differ. */
+static uint32_t
+boundary_maximum_residual (const uint16_t *residual,
+ const uint8_t *classes,
+ size_t rows,
+ size_t columns)
+{
+ uint32_t maximum = 0;
+
+ for (size_t row = 1; row + 1 < rows; row++)
+ for (size_t column = 2; column + 2 < columns; column++)
+ {
+ size_t pixel = row * columns + column;
+
+ if (classes[pixel] != ANTIFAKE_CLASS_EXCLUDED &&
+ maximum < residual[pixel])
+ maximum = residual[pixel];
+ }
+ return maximum;
+}
+
+/* Pairs are directed, so each undirected pair is counted twice. */
+static void
+boundary_adjacent_differences (const uint16_t *residual,
+ const uint8_t *skeleton,
+ size_t rows,
+ size_t columns,
+ uint32_t *difference_sum,
+ uint32_t *adjacent_count)
+{
+ const ptrdiff_t ring[8] = {
+ -(ptrdiff_t) columns - 1, -(ptrdiff_t) columns, 1 - (ptrdiff_t) columns,
+ 1, (ptrdiff_t) columns, (ptrdiff_t) columns + 1,
+ (ptrdiff_t) columns - 1, -1,
+ };
+
+ *difference_sum = 0;
+ *adjacent_count = 0;
+ for (size_t row = 3; row + 3 < rows; row++)
+ for (size_t column = 3; column + 3 < columns; column++)
+ {
+ size_t pixel = row * columns + column;
+
+ if (skeleton[pixel] != ANTIFAKE_CLASS_DARK)
+ continue;
+ for (size_t direction = 0; direction < 8; direction++)
+ {
+ size_t neighbor = (size_t) ((ptrdiff_t) pixel + ring[direction]);
+
+ if (skeleton[neighbor] != ANTIFAKE_CLASS_DARK)
+ continue;
+ uint32_t left = residual[pixel];
+ uint32_t right = residual[neighbor];
+
+ (*adjacent_count)++;
+ *difference_sum += left < right ? right - left : left - right;
+ }
+ }
+}
+
+/* round (difference_sum * 1000 / (adjacent_count * maximum)) in 32-bit
+ * registers: products wrap, the half-divisor is an arithmetic shift, division
+ * is signed and truncating. Only INT32_MIN / -1 (a native fault) is rejected. */
+static int
+boundary_rounded_ratio (uint32_t difference_sum,
+ uint32_t adjacent_count,
+ uint32_t maximum,
+ int32_t *score)
+{
+ uint32_t divisor = adjacent_count * maximum;
+ uint32_t numerator = difference_sum * BOUNDARY_SCORE_SCALE;
+
+ if (divisor == 0)
+ {
+ *score = goodix_milan_transform_s32 (numerator);
+ return 0;
+ }
+
+ int32_t signed_divisor = goodix_milan_transform_s32 (divisor);
+ int32_t half_divisor = goodix_milan_transform_sar32 (divisor, 1);
+ int32_t rounded_numerator =
+ goodix_milan_transform_s32 (numerator + (uint32_t) half_divisor);
+
+ if (rounded_numerator == INT32_MIN && signed_divisor == -1)
+ return -1;
+ *score = rounded_numerator / signed_divisor;
+ return 0;
+}
+
+int
+goodix_milan_antifake_boundary_score (
+ const uint16_t *residual,
+ const uint8_t *classes,
+ size_t rows,
+ size_t columns,
+ int32_t *score)
+{
+ uint8_t *thinned;
+ uint32_t maximum;
+ uint32_t difference_sum;
+ uint32_t adjacent_count;
+ int result = -1;
+
+ if (!residual || !classes || !score || rows < 7 ||
+ columns < 7 || columns > SIZE_MAX / rows)
+ return -1;
+
+ thinned = malloc (rows * columns);
+ if (!thinned)
+ return -1;
+ for (size_t i = 0; i < rows * columns; i++)
+ thinned[i] = classes[i] == ANTIFAKE_CLASS_DARK ? ANTIFAKE_CLASS_DARK : 0;
+
+ maximum = boundary_maximum_residual (residual, classes, rows, columns);
+ if (zhang_suen_thin (thinned, rows, columns, THINNING_MAX_ITERATIONS) != 0)
+ goto out;
+ boundary_adjacent_differences (residual, thinned, rows, columns,
+ &difference_sum, &adjacent_count);
+ result = boundary_rounded_ratio (difference_sum, adjacent_count, maximum,
+ score);
+
+out:
+ free (thinned);
+ return result;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/antifake/pair.c b/libfprint/drivers/goodix53x5/milan/antifake/pair.c
new file mode 100644
index 0000000..50b9ef4
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/antifake/pair.c
@@ -0,0 +1,290 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan anti-fake pair scoring
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/antifake/antifake.h"
+#include "milan/preprocess/state.h"
+#include "milan/transform-private.h"
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int
+antifake_descriptor_distance (const uint8_t *prior,
+ const uint8_t *current)
+{
+ int head0 = 0;
+ int head1 = 0;
+ int tail24 = 0;
+ int tail32 = 0;
+ int tail40 = 0;
+ int tail44 = 0;
+
+ for (size_t i = 0; i < 8; i++)
+ {
+ head0 += __builtin_popcount (
+ (unsigned) (prior[GOODIX_MILAN_ANTIFAKE_RECORD_DATA_8_OFFSET + i] ^
+ current[GOODIX_MILAN_ANTIFAKE_RECORD_DATA_8_OFFSET + i]));
+ head1 += __builtin_popcount (
+ (unsigned) (prior[GOODIX_MILAN_ANTIFAKE_RECORD_DATA_16_OFFSET + i] ^
+ current[GOODIX_MILAN_ANTIFAKE_RECORD_DATA_8_OFFSET + i]));
+ tail24 += __builtin_popcount (
+ (unsigned) (prior[GOODIX_MILAN_ANTIFAKE_RECORD_DATA_24_OFFSET + i] ^
+ current[GOODIX_MILAN_ANTIFAKE_RECORD_DATA_24_OFFSET + i]));
+ tail32 += __builtin_popcount (
+ (unsigned) (prior[GOODIX_MILAN_ANTIFAKE_RECORD_DATA_32_OFFSET + i] ^
+ current[GOODIX_MILAN_ANTIFAKE_RECORD_DATA_32_OFFSET + i]));
+ }
+ for (size_t i = 0; i < 4; i++)
+ {
+ tail40 += __builtin_popcount (
+ (unsigned) (prior[GOODIX_MILAN_ANTIFAKE_RECORD_DATA_40_OFFSET + i] ^
+ current[GOODIX_MILAN_ANTIFAKE_RECORD_DATA_40_OFFSET + i]));
+ tail44 += __builtin_popcount (
+ (unsigned) (prior[GOODIX_MILAN_ANTIFAKE_RECORD_DATA_40_OFFSET + i] ^
+ current[GOODIX_MILAN_ANTIFAKE_RECORD_DATA_44_OFFSET + i]));
+ }
+
+ int head = head0 < head1 ? head0 : head1;
+ int normal_tail = tail24 + tail32 + tail40;
+ int shifted_tail = tail24 + 64 + tail44 - tail32;
+
+ return head + (normal_tail < shifted_tail ? normal_tail : shifted_tail);
+}
+
+static int
+compare_int32 (const void *first,
+ const void *second)
+{
+ int32_t a = *(const int32_t *) first;
+ int32_t b = *(const int32_t *) second;
+
+ return (a > b) - (a < b);
+}
+
+static uint32_t
+antifake_coordinate_distance (int32_t prior_x,
+ int32_t prior_y,
+ int32_t transformed_x,
+ int32_t transformed_y)
+{
+ uint32_t dx = (uint32_t) prior_x * UINT32_C (0x100) -
+ (uint32_t) transformed_x;
+ uint32_t dy = (uint32_t) prior_y * UINT32_C (0x100) -
+ (uint32_t) transformed_y;
+ uint32_t distance = (uint32_t) goodix_milan_transform_sar32 (dx * dx, 8);
+
+ distance += (uint32_t) goodix_milan_transform_sar32 (dy * dy, 8);
+ return distance;
+}
+
+int
+goodix_milan_antifake_pair_metrics (
+ const GoodixMilanAntifakeBlob *prior,
+ size_t prior_size,
+ const GoodixMilanAntifakeBlob *current,
+ size_t current_size,
+ const int32_t current_to_prior[6],
+ int32_t metrics[5])
+{
+ enum {
+ rows = GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS,
+ columns = GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS,
+ };
+ int32_t inverse[6];
+ uint8_t overlap[rows * columns] = { 0 };
+ int32_t transformed_x[GOODIX_MILAN_ANTIFAKE_RECORD_CAPACITY];
+ int32_t transformed_y[GOODIX_MILAN_ANTIFAKE_RECORD_CAPACITY];
+ int16_t current_to_prior_index[GOODIX_MILAN_ANTIFAKE_RECORD_CAPACITY];
+ int16_t prior_to_current_index[GOODIX_MILAN_ANTIFAKE_RECORD_CAPACITY];
+ uint8_t current_valid[GOODIX_MILAN_ANTIFAKE_RECORD_CAPACITY] = { 0 };
+ int32_t distances[GOODIX_MILAN_ANTIFAKE_RECORD_CAPACITY];
+ uint32_t prior_count;
+ uint32_t current_count;
+ size_t distance_count = 0;
+ int32_t current_valid_count = 0;
+ int32_t prior_valid_count = 0;
+
+ if (!prior || prior_size < GOODIX_MILAN_ANTIFAKE_SIZE || !current ||
+ current_size < GOODIX_MILAN_ANTIFAKE_SIZE || !current_to_prior ||
+ !metrics)
+ return -1;
+ memset (metrics, 0, 5 * sizeof(*metrics));
+ prior_count = goodix_milan_antifake_candidate_count (prior);
+ current_count = goodix_milan_antifake_candidate_count (current);
+ if (prior_count > GOODIX_MILAN_ANTIFAKE_RECORD_CAPACITY ||
+ current_count > GOODIX_MILAN_ANTIFAKE_RECORD_CAPACITY)
+ return -1;
+ memset (current_to_prior_index, 0xff, sizeof(current_to_prior_index));
+ memset (prior_to_current_index, 0xff, sizeof(prior_to_current_index));
+ if (goodix_milan_transform_invert_s32_checked (
+ current_to_prior, inverse) != 0)
+ return -1;
+
+ for (int32_t y = 0; y < rows; y++)
+ for (int32_t x = 0; x < columns; x++)
+ {
+ size_t pixel = (size_t) y * columns + (size_t) x;
+ int32_t source_x;
+ int32_t source_y;
+
+ if ((goodix_milan_antifake_const_mask (prior)[pixel / 8] &
+ (1U << (pixel & 7))) == 0)
+ continue;
+ source_x = goodix_milan_transform_sar32 (
+ (uint32_t) goodix_milan_transform_affine_s32 (
+ inverse[0], (uint32_t) x, inverse[1], (uint32_t) y,
+ (uint32_t) inverse[2]) + UINT32_C (0x80),
+ 8);
+ source_y = goodix_milan_transform_sar32 (
+ (uint32_t) goodix_milan_transform_affine_s32 (
+ inverse[3], (uint32_t) x, inverse[4], (uint32_t) y,
+ (uint32_t) inverse[5]) + UINT32_C (0x80),
+ 8);
+ if (source_x >= 0 && source_x < columns && source_y >= 0 &&
+ source_y < rows)
+ {
+ size_t source_pixel =
+ (size_t) source_y * columns + (size_t) source_x;
+
+ overlap[pixel] =
+ (goodix_milan_antifake_const_mask (current)[source_pixel / 8] &
+ (1U << (source_pixel & 7))) != 0;
+ }
+ }
+
+ for (uint32_t current_index = 0; current_index < current_count;
+ current_index++)
+ {
+ const uint8_t *current_record = goodix_milan_antifake_const_record (
+ current, current_index);
+ int32_t x = goodix_milan_antifake_record_x (current_record);
+ int32_t y = goodix_milan_antifake_record_y (current_record);
+ int32_t rounded_x;
+ int32_t rounded_y;
+ uint32_t best_distance = UINT32_MAX;
+ int16_t best_index = -1;
+
+ transformed_x[current_index] = goodix_milan_transform_affine_s32 (
+ current_to_prior[0], (uint32_t) x, current_to_prior[1],
+ (uint32_t) y, (uint32_t) current_to_prior[2]);
+ transformed_y[current_index] = goodix_milan_transform_affine_s32 (
+ current_to_prior[3], (uint32_t) x, current_to_prior[4],
+ (uint32_t) y, (uint32_t) current_to_prior[5]);
+ rounded_x = goodix_milan_transform_sar32 (
+ (uint32_t) transformed_x[current_index] + UINT32_C (0x80), 8);
+ rounded_y = goodix_milan_transform_sar32 (
+ (uint32_t) transformed_y[current_index] + UINT32_C (0x80), 8);
+ if (rounded_x < 0 || rounded_x >= columns || rounded_y < 0 ||
+ rounded_y >= rows || !overlap[rounded_y * columns + rounded_x])
+ continue;
+ current_valid[current_index] = 1;
+ current_valid_count++;
+ for (uint32_t prior_index = 0; prior_index < prior_count; prior_index++)
+ {
+ const uint8_t *prior_record = goodix_milan_antifake_const_record (
+ prior, prior_index);
+ int32_t prior_x = goodix_milan_antifake_record_x (prior_record);
+ int32_t prior_y = goodix_milan_antifake_record_y (prior_record);
+ uint32_t candidate = antifake_coordinate_distance (
+ prior_x, prior_y, transformed_x[current_index],
+ transformed_y[current_index]);
+
+ if (candidate < best_distance)
+ {
+ best_distance = candidate;
+ best_index = (int16_t) prior_index;
+ }
+ }
+ if (best_distance <= 0x400)
+ current_to_prior_index[current_index] = best_index;
+ }
+
+ for (uint32_t prior_index = 0; prior_index < prior_count; prior_index++)
+ {
+ const uint8_t *prior_record = goodix_milan_antifake_const_record (
+ prior, prior_index);
+ int32_t prior_x = goodix_milan_antifake_record_x (prior_record);
+ int32_t prior_y = goodix_milan_antifake_record_y (prior_record);
+ uint32_t best_distance = UINT32_MAX;
+ int16_t best_index = -1;
+
+ if (prior_x < 0 || prior_x >= columns || prior_y < 0 || prior_y >= rows ||
+ !overlap[prior_y * columns + prior_x])
+ continue;
+ prior_valid_count++;
+ for (uint32_t current_index = 0; current_index < current_count;
+ current_index++)
+ {
+ uint32_t candidate;
+
+ if (!current_valid[current_index])
+ continue;
+ candidate = antifake_coordinate_distance (
+ prior_x, prior_y, transformed_x[current_index],
+ transformed_y[current_index]);
+ if (candidate < best_distance)
+ {
+ best_distance = candidate;
+ best_index = (int16_t) current_index;
+ }
+ }
+ if (best_distance <= 0x400)
+ prior_to_current_index[prior_index] = best_index;
+ }
+
+ for (uint32_t prior_index = 0; prior_index < prior_count; prior_index++)
+ {
+ int16_t current_index = prior_to_current_index[prior_index];
+
+ if (current_index >= 0 &&
+ current_to_prior_index[current_index] == (int16_t) prior_index)
+ distances[distance_count++] = antifake_descriptor_distance (
+ goodix_milan_antifake_const_record (prior, prior_index),
+ goodix_milan_antifake_const_record (current,
+ (size_t) current_index));
+ }
+ metrics[1] = (int32_t) distance_count;
+ if (distance_count == 0)
+ return 0;
+
+ int32_t valid_total = prior_valid_count + current_valid_count;
+
+ metrics[2] = valid_total == 0
+ ? (int32_t) distance_count << 13
+ : (valid_total / 2 + (int32_t) distance_count * 0x2000) /
+ valid_total;
+ metrics[3] = prior_valid_count == 0
+ ? current_valid_count * 0x1000
+ : (prior_valid_count / 2 + current_valid_count * 0x1000) /
+ prior_valid_count;
+ qsort (distances, distance_count, sizeof (distances[0]), compare_int32);
+ metrics[4] = distances[(distance_count - 1) / 2];
+ return 0;
+}
+
+int
+goodix_milan_antifake_score_pair (
+ const GoodixMilanAntifakeBlob *prior,
+ size_t prior_size,
+ const GoodixMilanAntifakeBlob *current,
+ size_t current_size,
+ const int32_t current_to_prior[6],
+ int32_t *score)
+{
+ int32_t metrics[5];
+
+ if (!score || goodix_milan_antifake_pair_metrics (
+ prior, prior_size, current, current_size, current_to_prior,
+ metrics) != 0)
+ return -1;
+ *score = metrics[1] == 0 ? -1 : metrics[4];
+ return 0;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/antifake/signal.c b/libfprint/drivers/goodix53x5/milan/antifake/signal.c
new file mode 100644
index 0000000..396e318
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/antifake/signal.c
@@ -0,0 +1,407 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan anti-fake signal analysis
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/antifake/antifake.h"
+#include "milan/print.h"
+#include "milan/transform-private.h"
+
+#include <limits.h>
+#include <stdint.h>
+#include <string.h>
+
+/* Profile-9 anti-fake signal stages recovered from FUN_18003a150,
+ * FUN_18003a9b0, FUN_18003aff0, and FUN_180039c10. */
+#define ANTIFAKE_RESIDUAL_BASELINE 0x1bb7
+#define ANTIFAKE_EDGE_REPLICATE_TYPE_17 0x11
+#define ANTIFAKE_NEIGHBORHOOD_SIZE 9
+#define ANTIFAKE_NEIGHBORHOOD_MEDIAN 4
+#define ANTIFAKE_HISTOGRAM_BINS 4096
+#define ANTIFAKE_HISTOGRAM_LIMIT 0x0fff
+#define ANTIFAKE_TAIL_COUNT_DIVISOR 50
+#define ANTIFAKE_IMPULSE_CUTOFF_NUMERATOR 11
+#define ANTIFAKE_IMPULSE_CUTOFF_DENOMINATOR 10
+#define ANTIFAKE_ROUGHNESS_MEDIAN_SCALE 5
+#define ANTIFAKE_ROUGHNESS_CENTER_SCALE 2
+#define ANTIFAKE_TEXTURE_BORDER 4
+#define ANTIFAKE_TEXTURE_RADIUS 5
+#define ANTIFAKE_HIGHPASS_CENTER 0x2000
+#define ANTIFAKE_TEXTURE_SCALE 3
+#define ANTIFAKE_VARIATION_Q12_ONE 0x1000
+
+int
+goodix_milan_antifake_residual (
+ const uint16_t *calibration,
+ const uint16_t *raw_frame,
+ size_t rows,
+ size_t columns,
+ int32_t sensor_offset,
+ uint16_t chip_type,
+ uint16_t *residual)
+{
+ size_t count;
+
+ if (!calibration || !raw_frame || !residual || rows < 2 || columns < 2 ||
+ columns > SIZE_MAX / rows)
+ return -1;
+ count = rows * columns;
+ if (count > SIZE_MAX / sizeof (*residual))
+ return -1;
+
+ memset (residual, 0, count * sizeof (*residual));
+ for (size_t row = 1; row + 1 < rows; row++)
+ for (size_t column = 1; column + 1 < columns; column++)
+ {
+ size_t i = row * columns + column;
+ int32_t value = (int32_t) calibration[i] - raw_frame[i] -
+ sensor_offset - ANTIFAKE_RESIDUAL_BASELINE;
+
+ residual[i] = (uint16_t) value;
+ }
+
+ if (chip_type == GOODIX_MILAN_PRINT_SENSOR_TYPE ||
+ chip_type == ANTIFAKE_EDGE_REPLICATE_TYPE_17)
+ {
+ memcpy (residual, residual + columns,
+ columns * sizeof (*residual));
+ memcpy (residual + (rows - 1) * columns,
+ residual + (rows - 2) * columns,
+ columns * sizeof (*residual));
+ for (size_t row = 0; row < rows; row++)
+ {
+ residual[row * columns] = residual[row * columns + 1];
+ residual[row * columns + columns - 1] =
+ residual[row * columns + columns - 2];
+ }
+ }
+
+ return 0;
+}
+
+static uint16_t
+antifake_median9_u16 (const uint16_t values[ANTIFAKE_NEIGHBORHOOD_SIZE])
+{
+ uint16_t sorted[ANTIFAKE_NEIGHBORHOOD_SIZE];
+
+ memcpy (sorted, values, sizeof (sorted));
+ for (size_t i = 1; i < ANTIFAKE_NEIGHBORHOOD_SIZE; i++)
+ {
+ uint16_t value = sorted[i];
+ size_t j = i;
+
+ while (j > 0 && value < sorted[j - 1])
+ {
+ sorted[j] = sorted[j - 1];
+ j--;
+ }
+ sorted[j] = value;
+ }
+ return sorted[ANTIFAKE_NEIGHBORHOOD_MEDIAN];
+}
+
+static int32_t
+antifake_local_roughness (const uint16_t *residual,
+ size_t rows,
+ size_t columns,
+ ptrdiff_t x,
+ ptrdiff_t y)
+{
+ int32_t roughness = 0;
+
+ if (x < 1)
+ x = 1;
+ if (x > (ptrdiff_t) columns - 2)
+ x = (ptrdiff_t) columns - 2;
+ if (y < 1)
+ y = 1;
+ if (y > (ptrdiff_t) rows - 2)
+ y = (ptrdiff_t) rows - 2;
+ uint16_t center = residual[(size_t) y * columns + (size_t) x];
+ for (ptrdiff_t dy = -1; dy <= 1; dy++)
+ for (ptrdiff_t dx = -1; dx <= 1; dx++)
+ {
+ uint16_t neighbor = residual[(size_t) (y + dy) * columns +
+ (size_t) (x + dx)];
+ roughness += center < neighbor ? neighbor - center :
+ center - neighbor;
+ }
+ return roughness;
+}
+
+int
+goodix_milan_antifake_impulse_filter (
+ uint16_t *residual,
+ size_t rows,
+ size_t columns,
+ int32_t *threshold)
+{
+ uint32_t histogram[ANTIFAKE_HISTOGRAM_BINS] = { 0 };
+
+ if (!residual || !threshold || rows < 3 || columns < 3 ||
+ columns > SIZE_MAX / rows || rows * columns > INT32_MAX)
+ return -1;
+ for (size_t row = 1; row + 1 < rows; row++)
+ for (size_t column = 1; column + 1 < columns; column++)
+ if (residual[row * columns + column] < ANTIFAKE_HISTOGRAM_LIMIT)
+ histogram[residual[row * columns + column]]++;
+ for (int value = ANTIFAKE_HISTOGRAM_BINS - 2; value >= 0; value--)
+ histogram[value] += histogram[value + 1];
+
+ int32_t selected = 0;
+ int32_t minimum_count =
+ (int32_t) (rows * columns) / ANTIFAKE_TAIL_COUNT_DIVISOR;
+ for (int32_t value = ANTIFAKE_HISTOGRAM_BINS - 1; value >= 0; value--)
+ if ((int32_t) histogram[value] > minimum_count)
+ {
+ selected = value;
+ break;
+ }
+ *threshold = selected;
+ uint16_t cutoff =
+ (uint16_t) ((selected * ANTIFAKE_IMPULSE_CUTOFF_NUMERATOR) /
+ ANTIFAKE_IMPULSE_CUTOFF_DENOMINATOR);
+ for (size_t row = 0; row < rows; row++)
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t pixel = row * columns + column;
+
+ if (residual[pixel] < cutoff)
+ continue;
+ int32_t roughness[ANTIFAKE_NEIGHBORHOOD_SIZE];
+ size_t roughness_index = 0;
+ for (ptrdiff_t dy = -1; dy <= 1; dy++)
+ for (ptrdiff_t dx = -1; dx <= 1; dx++)
+ roughness[roughness_index++] = antifake_local_roughness (
+ residual, rows, columns, (ptrdiff_t) column + dx,
+ (ptrdiff_t) row + dy);
+ int32_t sorted_roughness[ANTIFAKE_NEIGHBORHOOD_SIZE];
+ memcpy (sorted_roughness, roughness, sizeof (sorted_roughness));
+ for (size_t i = 1; i < ANTIFAKE_NEIGHBORHOOD_SIZE; i++)
+ {
+ int32_t value = sorted_roughness[i];
+ size_t j = i;
+
+ while (j > 0 && value < sorted_roughness[j - 1])
+ {
+ sorted_roughness[j] = sorted_roughness[j - 1];
+ j--;
+ }
+ sorted_roughness[j] = value;
+ }
+ if (sorted_roughness[ANTIFAKE_NEIGHBORHOOD_MEDIAN] *
+ ANTIFAKE_ROUGHNESS_MEDIAN_SCALE <=
+ roughness[ANTIFAKE_NEIGHBORHOOD_MEDIAN] *
+ ANTIFAKE_ROUGHNESS_CENTER_SCALE)
+ {
+ uint16_t neighborhood[ANTIFAKE_NEIGHBORHOOD_SIZE];
+ size_t neighborhood_index = 0;
+ size_t count = rows * columns;
+
+ /*
+ * Vendor replacement uses flat adjacency, so edge columns intentionally
+ * wrap; only allocation-end offsets use the safe coordinate-clamped
+ * fallback.
+ */
+ if (pixel >= columns + 1 && pixel + columns + 1 < count)
+ {
+ for (ptrdiff_t dy = -1; dy <= 1; dy++)
+ for (ptrdiff_t dx = -1; dx <= 1; dx++)
+ neighborhood[neighborhood_index++] = residual[
+ (size_t) ((ptrdiff_t) pixel +
+ dy * (ptrdiff_t) columns + dx)];
+ }
+ else
+ {
+ ptrdiff_t center_x = (ptrdiff_t) column;
+ ptrdiff_t center_y = (ptrdiff_t) row;
+
+ if (center_x < 1)
+ center_x = 1;
+ if (center_x > (ptrdiff_t) columns - 2)
+ center_x = (ptrdiff_t) columns - 2;
+ if (center_y < 1)
+ center_y = 1;
+ if (center_y > (ptrdiff_t) rows - 2)
+ center_y = (ptrdiff_t) rows - 2;
+ for (ptrdiff_t dy = -1; dy <= 1; dy++)
+ for (ptrdiff_t dx = -1; dx <= 1; dx++)
+ neighborhood[neighborhood_index++] =
+ residual[(size_t) (center_y + dy) * columns +
+ (size_t) (center_x + dx)];
+ }
+ residual[pixel] = antifake_median9_u16 (neighborhood);
+ }
+ }
+ return 0;
+}
+
+int
+goodix_milan_antifake_statistics (
+ const uint16_t *residual,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ int32_t *texture,
+ int32_t *mean)
+{
+ uint64_t masked_sum = 0;
+ uint64_t texture_sum = 0;
+ size_t masked_count = 0;
+ size_t texture_count = 0;
+
+ if (!residual || !mask || !texture || !mean || rows == 0 || columns == 0 ||
+ columns > SIZE_MAX / rows)
+ return -1;
+
+ for (size_t i = 0; i < rows * columns; i++)
+ if (mask[i] != 0)
+ {
+ masked_sum += residual[i];
+ masked_count++;
+ }
+ *mean = masked_count == 0 ?
+ 0 :
+ (int32_t) ((masked_sum + masked_count / 2) / masked_count);
+
+ if (rows > 2 * ANTIFAKE_TEXTURE_BORDER &&
+ columns > 2 * ANTIFAKE_TEXTURE_BORDER)
+ {
+ for (size_t row = ANTIFAKE_TEXTURE_BORDER;
+ row + ANTIFAKE_TEXTURE_BORDER < rows;
+ row++)
+ for (size_t column = ANTIFAKE_TEXTURE_BORDER;
+ column + ANTIFAKE_TEXTURE_BORDER < columns;
+ column++)
+ {
+ size_t i = row * columns + column;
+ uint32_t local_sum = 0;
+ size_t top = row > ANTIFAKE_TEXTURE_RADIUS ?
+ row - ANTIFAKE_TEXTURE_RADIUS : 0;
+ size_t bottom = row + ANTIFAKE_TEXTURE_RADIUS < rows ?
+ row + ANTIFAKE_TEXTURE_RADIUS : rows - 1;
+ size_t left = column > ANTIFAKE_TEXTURE_RADIUS ?
+ column - ANTIFAKE_TEXTURE_RADIUS : 0;
+ size_t right = column + ANTIFAKE_TEXTURE_RADIUS < columns ?
+ column + ANTIFAKE_TEXTURE_RADIUS : columns - 1;
+ size_t area = (bottom - top + 1) * (right - left + 1);
+
+ if (mask[i] == 0)
+ continue;
+ for (size_t y = top; y <= bottom; y++)
+ for (size_t x = left; x <= right; x++)
+ local_sum += residual[y * columns + x];
+ uint16_t local_mean = (uint16_t) ((local_sum + area / 2) / area);
+ int16_t highpass = (int16_t) ((int16_t) residual[i] -
+ (int16_t) local_mean +
+ ANTIFAKE_HIGHPASS_CENTER);
+ uint16_t encoded = (uint16_t) highpass;
+
+ texture_sum += encoded > ANTIFAKE_HIGHPASS_CENTER ?
+ encoded - ANTIFAKE_HIGHPASS_CENTER :
+ ANTIFAKE_HIGHPASS_CENTER - encoded;
+ texture_count++;
+ }
+ }
+ *texture = texture_count == 0 ?
+ 0 :
+ (int32_t) (((texture_sum + texture_count / 2) *
+ ANTIFAKE_TEXTURE_SCALE) /
+ texture_count);
+ return 0;
+}
+
+static uint32_t
+antifake_integer_sqrt (uint32_t value)
+{
+ uint32_t root = 0;
+
+ if (value < 2)
+ return value;
+ for (uint32_t bit = 0x8000, shift = 15; bit != 0; bit >>= 1, shift--)
+ {
+ uint32_t candidate = (bit + root * 2) << shift;
+
+ if (candidate <= value)
+ {
+ root += bit;
+ value -= candidate;
+ }
+ }
+ return root;
+}
+
+int
+goodix_milan_antifake_block_variation (
+ const uint16_t *residual,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ size_t block_size,
+ int32_t *variation)
+{
+ uint32_t sum = 0;
+ uint32_t square_sum = 0;
+ uint32_t valid_count = 0;
+
+ if (!residual || !mask || !variation || block_size == 0 ||
+ rows / block_size < 1 || columns / block_size < 1 ||
+ columns > SIZE_MAX / rows)
+ return -1;
+
+ size_t block_rows = rows / block_size - 1;
+ size_t block_columns = columns / block_size - 1;
+ size_t start_row = (rows - block_rows * block_size) / 2;
+ size_t start_column = (columns - block_columns * block_size) / 2;
+
+ for (size_t block_row = 0; block_row < block_rows; block_row++)
+ for (size_t block_column = 0; block_column < block_columns; block_column++)
+ {
+ size_t row0 = start_row + block_row * block_size;
+ size_t column0 = start_column + block_column * block_size;
+ uint16_t maximum = 0;
+ int valid = 1;
+
+ for (size_t y = 0; y < block_size; y++)
+ for (size_t x = 0; x < block_size; x++)
+ {
+ size_t i = (row0 + y) * columns + column0 + x;
+
+ if (maximum <= residual[i])
+ maximum = residual[i];
+ if (mask[i] == 0)
+ valid = 0;
+ }
+ if (valid)
+ {
+ sum += maximum;
+ square_sum += (uint32_t) maximum * maximum;
+ valid_count++;
+ }
+ }
+
+ uint32_t mean = 0;
+ int32_t mean_square = 0;
+ if (valid_count != 0)
+ {
+ uint32_t rounded_square_sum = square_sum + valid_count / 2;
+
+ mean = (sum + valid_count / 2) / valid_count;
+ mean_square = goodix_milan_transform_s32 (rounded_square_sum) /
+ (int32_t) valid_count;
+ }
+ uint32_t variance = (uint32_t) mean_square - mean * mean;
+ if ((int32_t) variance < 0)
+ variance = 0;
+ uint32_t scaled =
+ antifake_integer_sqrt (variance) * ANTIFAKE_VARIATION_Q12_ONE;
+
+ *variation = mean == 0 ? (int32_t) scaled :
+ (int32_t) ((scaled + mean / 2) / mean);
+ return 0;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/capacity.h b/libfprint/drivers/goodix53x5/milan/capacity.h
new file mode 100644
index 0000000..d646fa9
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/capacity.h
@@ -0,0 +1,17 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan template capacities
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#define GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY 50
+#define GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT 40
+#define GOODIX_MILAN_TEMPLATE_RELATION_CAPACITY \
+ (GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY * \
+ (GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY - 1) / 2)
diff --git a/libfprint/drivers/goodix53x5/milan/core.c b/libfprint/drivers/goodix53x5/milan/core.c
new file mode 100644
index 0000000..649fb87
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/core.c
@@ -0,0 +1,3033 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan image preprocessing
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+/* Produces profile-9/type-12 processed images, quality, and retained state.
+ * Native owners are preprocessor, FUN_18006d540, FUN_180067500, and
+ * FUN_180069820. */
+
+#include "milan/milan.h"
+#include "milan/private.h"
+#include "milan/preprocess/gain.h"
+#include "milan/preprocess/state.h"
+#include "milan/study/order.h"
+#include "milan/study/policy.h"
+
+#include <limits.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define MILAN_ADC_MAX UINT16_C(0x0fff)
+#define MILAN_FIXED_ONE UINT32_C(0x2000)
+#define MILAN_PROFILE9_SETUP_OFFSET UINT16_C(7095)
+#define MILAN_PROFILE9_UPDATE_BASE UINT16_C(9000)
+#define MILAN_PROFILE9_RAW_ADMISSION_SAMPLE_MIN_EXCLUSIVE UINT16_C(100)
+#define MILAN_PROFILE9_RAW_ADMISSION_SAMPLE_MAX_EXCLUSIVE UINT16_C(0x0ed8)
+
+enum
+{
+ MILAN_QUALITY_PERCENT_SCALE = 100,
+ MILAN_QUALITY_SCORE_BIN_COUNT = 101,
+ MILAN_QUALITY_Q8_ONE = 0x100,
+ MILAN_QUALITY_Q8_SHIFT = 8,
+ MILAN_QUALITY_Q16_ONE = 0x10000,
+ MILAN_QUALITY_Q16_SHIFT = 16,
+ MILAN_QUALITY_PATCH_REDUCTION_CEILING = 70,
+ MILAN_QUALITY_VALID_COVERAGE_DELTA = 0x3333,
+ MILAN_QUALITY_GRADIENT_WINDOW_RECIPROCAL_Q16 = 291,
+ MILAN_QUALITY_COVERAGE_THRESHOLD = 0x78,
+ MILAN_QUALITY_SELECTION_THRESHOLD = 100,
+ MILAN_QUALITY_PATCH_WIDTH = 25,
+ MILAN_QUALITY_PATCH_RADIUS = 12,
+ MILAN_QUALITY_PATCH_STRIDE = 8,
+ MILAN_QUALITY_PATCH_GRADIENT_FLOOR = 25,
+ MILAN_QUALITY_PATCH_MINIMUM_VALID_DIVISOR = 2,
+ MILAN_QUALITY_PATCH_MINIMUM_SELECTED_DIVISOR = 6,
+ MILAN_QUALITY_REFINED_MASK_MARKER = 0x20,
+ MILAN_QUALITY_RING_SIZE = 8,
+ MILAN_QUALITY_RING_INDEX_MASK = 7,
+ MILAN_QUALITY_RING_CONTRAST_DELTA = 4,
+ MILAN_QUALITY_RING_TRANSITION_LIMIT = 3,
+ MILAN_QUALITY_RING_TARGET_CLASS = 4,
+ MILAN_QUALITY_RING_UNCLASSIFIED = 9,
+ MILAN_QUALITY_RING_HISTOGRAM_SIZE = 10,
+};
+
+static const uint16_t milan_update_kernel[5] = {
+ 7869, 15328, 19142, 15328, 7869,
+};
+
+static const uint16_t milan_quality_gaussian7_kernel[5] = {
+ 3571, 16004, 26386, 16004, 3571,
+};
+
+static const uint16_t milan_quality_gaussian6_kernel[3] = {
+ 21845, 21845, 21845,
+};
+
+static int first_update_frame_core (const uint16_t *normalized_live,
+ const uint16_t *setup_map,
+ const uint16_t *application_map,
+ const uint16_t *application_gain_map,
+ uint16_t *persistent_auxiliary_gain,
+ uint32_t auxiliary_samples,
+ GoodixMilanPreprocessState *state,
+ uint32_t calibration_ready,
+ size_t rows,
+ size_t columns,
+ uint16_t *gain_map,
+ uint16_t *output,
+ uint16_t *optional_plane0);
+static void profile9_update_source (const uint16_t *normalized_live,
+ const uint16_t *setup_map,
+ size_t count,
+ uint16_t *output);
+static int profile9_normalize_outer_edges (uint16_t *frame,
+ size_t rows,
+ size_t columns);
+static void milan_profile9_encode_metadata (uint8_t *image,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ int mode,
+ int apply_mask);
+static void milan_profile9_make_reciprocal_plane (
+ const uint16_t *application_gain,
+ size_t count,
+ uint16_t *output);
+static int preprocess_refine_core (const uint16_t *source,
+ const uint8_t *mask,
+ uint16_t valid_percent,
+ size_t rows,
+ size_t columns,
+ uint16_t *centered,
+ uint8_t *output);
+static int milan_profile9_post_render (
+ GoodixMilanPreprocessState *state,
+ const uint16_t *normalized_live,
+ const uint16_t *setup_map,
+ const uint8_t *render_mask,
+ const uint16_t *working,
+ const uint16_t *optional_plane0,
+ const uint16_t *reciprocal_plane,
+ const uint8_t *selected,
+ const uint8_t *selection_mask,
+ int selected_refined,
+ GoodixMilanPreprocessPurpose purpose,
+ uint32_t *calibration_ready,
+ const uint8_t **first_metadata_mask,
+ uint8_t **first_metadata_owned_mask,
+ int *first_metadata_mode,
+ int *first_metadata_apply);
+
+static void
+profile9_initialize_gain_state (GoodixMilanPreprocessState *state)
+{
+ const size_t count = GOODIX_MILAN_SENSOR_PIXELS;
+ uint32_t sum = 0;
+ uint32_t mean;
+
+ if (state->sample_count == 0)
+ {
+ for (size_t i = 0; i < count; i++)
+ {
+ state->calibration_map[i] = 0;
+ state->auxiliary_gain_map[i] = MILAN_FIXED_ONE;
+ state->secondary_auxiliary_gain_map[i] = MILAN_FIXED_ONE;
+ state->application_gain_map[i] = MILAN_FIXED_ONE;
+ }
+ state->auxiliary_sample_count = 0;
+ state->application_gain_initialized = 1;
+ return;
+ }
+
+ if (state->sample_count <= 3)
+ {
+ for (size_t i = 0; i < count; i++)
+ state->application_gain_map[i] = MILAN_FIXED_ONE;
+ state->application_gain_initialized = 1;
+ return;
+ }
+
+ if (state->application_gain_initialized)
+ return;
+
+ for (size_t i = 0; i < count; i++)
+ sum += state->calibration_map[i];
+ mean = (sum + count / 2) / count;
+ if (mean == 0)
+ {
+ state->sample_count = 0;
+ state->application_gain_initialized = 1;
+ return;
+ }
+
+ for (size_t i = 0; i < count; i++)
+ state->application_gain_map[i] =
+ (uint16_t) (((uint32_t) state->calibration_map[i] * MILAN_FIXED_ONE +
+ mean / 2) /
+ mean);
+ state->application_gain_initialized = 1;
+}
+
+void
+goodix_milan_preprocess_reset (GoodixMilanPreprocessState *state)
+{
+ if (state)
+ {
+ memset (state, 0, sizeof(*state));
+ for (size_t i = 0; i < GOODIX_MILAN_SENSOR_PIXELS; i++)
+ {
+ state->auxiliary_gain_map[i] = MILAN_FIXED_ONE;
+ state->secondary_auxiliary_gain_map[i] = MILAN_FIXED_ONE;
+ state->application_gain_map[i] = MILAN_FIXED_ONE;
+ }
+ }
+}
+
+int
+goodix_milan_preprocess (GoodixMilanPreprocessState *state,
+ GoodixMilanProfileState *profile_state,
+ const uint16_t *setup_frame,
+ const uint16_t *live_frame,
+ GoodixMilanPreprocessPurpose purpose,
+ uint8_t *output,
+ int *quality,
+ int *coverage)
+{
+ const size_t count = GOODIX_MILAN_SENSOR_PIXELS;
+ uint16_t *setup_map = NULL;
+ uint16_t *normalized_live = NULL;
+ uint16_t *difference = NULL;
+ uint16_t *gain = NULL;
+ uint16_t *working = NULL;
+ uint16_t *refined_source = NULL;
+ uint16_t *optional_plane0 = NULL;
+ uint16_t *reciprocal_plane = NULL;
+ uint8_t *mask = NULL;
+ uint8_t *contrast = NULL;
+ uint8_t *refined = NULL;
+ uint8_t *broken_mask = NULL;
+ uint8_t *contrast_mask = NULL;
+ uint8_t *selection_mask = NULL;
+ uint32_t rounded_mean;
+ uint16_t threshold;
+ uint16_t valid_percent;
+ uint16_t refined_percent;
+ size_t admitted_pixels = 0;
+ size_t refined_pixels = 0;
+ uint32_t auxiliary_samples;
+ const uint8_t *first_metadata_mask;
+ uint8_t *first_metadata_owned_mask = NULL;
+ int selected_refined;
+ int first_metadata_mode;
+ int first_metadata_apply;
+ int metadata_mode;
+ int apply_metadata_mask;
+ int classification_status;
+ int post_status;
+ int result = -1;
+
+ if (state)
+ {
+ state->primary_contrast_valid = 0;
+ state->extraction_auxiliary_valid = 0;
+ state->post_render.primary_metric = 0;
+ state->post_render.fallback_metric = 0;
+ state->post_render.disagreement = 0;
+ state->post_render.component_score = 0;
+ state->post_render.component_flag = 0;
+ state->post_render.quality_gate = 0;
+ state->post_render.update_applied = 0;
+ state->post_render.status = 0;
+ }
+ if (!state || !profile_state || !setup_frame || !live_frame ||
+ (purpose != GOODIX_MILAN_PURPOSE_IDENTIFY &&
+ purpose != GOODIX_MILAN_PURPOSE_ENROLL) ||
+ !output || !quality || !coverage)
+ return -1;
+ *quality = 0;
+ *coverage = 0;
+ setup_map = malloc (count * sizeof(*setup_map));
+ normalized_live = malloc (count * sizeof(*normalized_live));
+ difference = malloc (count * sizeof(*difference));
+ gain = malloc (count * sizeof(*gain));
+ working = malloc (count * sizeof(*working));
+ refined_source = malloc (count * sizeof(*refined_source));
+ optional_plane0 = malloc (count * sizeof(*optional_plane0));
+ reciprocal_plane = malloc (count * sizeof(*reciprocal_plane));
+ mask = malloc (count);
+ contrast = malloc (count);
+ refined = malloc (count);
+ broken_mask = malloc (count);
+ contrast_mask = malloc (count);
+ selection_mask = malloc (count);
+ if (!setup_map || !normalized_live || !difference || !gain || !working ||
+ !refined_source || !optional_plane0 || !reciprocal_plane || !mask ||
+ !contrast || !refined || !broken_mask || !contrast_mask ||
+ !selection_mask)
+ goto out;
+
+ memcpy (setup_map, setup_frame, count * sizeof(*setup_map));
+ memcpy (normalized_live, live_frame, count * sizeof(*normalized_live));
+ for (size_t i = 0; i < count; i++)
+ {
+ if (setup_map[i] > MILAN_ADC_MAX)
+ setup_map[i] = MILAN_ADC_MAX;
+ }
+ if (!goodix_milan_preprocess_clamp_and_admit_raw (
+ normalized_live, GOODIX_MILAN_SENSOR_ROWS,
+ GOODIX_MILAN_SENSOR_COLUMNS, 2, 15))
+ {
+ result = GOODIX_MILAN_PREPROCESS_RETRY_RAW_ADMISSION;
+ goto out;
+ }
+ if (goodix_milan_preprocess_make_setup_map (
+ setup_map, GOODIX_MILAN_SENSOR_ROWS, GOODIX_MILAN_SENSOR_COLUMNS,
+ setup_map, &rounded_mean) != 0 ||
+ profile9_normalize_outer_edges (
+ normalized_live, GOODIX_MILAN_SENSOR_ROWS,
+ GOODIX_MILAN_SENSOR_COLUMNS) != 0 ||
+ goodix_milan_preprocess_build_mask (
+ normalized_live, setup_map, GOODIX_MILAN_SENSOR_ROWS,
+ GOODIX_MILAN_SENSOR_COLUMNS, mask, &threshold, &valid_percent) != 0 ||
+ goodix_milan_preprocess_no_update_frame (
+ normalized_live, setup_map, GOODIX_MILAN_SENSOR_ROWS,
+ GOODIX_MILAN_SENSOR_COLUMNS, difference) != 0 ||
+ goodix_milan_profile9_build_contrast_mask (
+ normalized_live, setup_map, GOODIX_MILAN_SENSOR_ROWS,
+ GOODIX_MILAN_SENSOR_COLUMNS, contrast_mask, &admitted_pixels) != 0)
+ goto out;
+
+ profile9_initialize_gain_state (state);
+ milan_profile9_make_reciprocal_plane (
+ state->application_gain_map, count, reciprocal_plane);
+ goodix_milan_profile9_update_gain_ready (
+ state->auxiliary_sample_count, state->sample_count,
+ &profile_state->calibration_ready);
+
+ if (admitted_pixels * 10 > count * 9)
+ {
+ auxiliary_samples = state->auxiliary_sample_count;
+ if (first_update_frame_core (
+ normalized_live, setup_map, state->calibration_map,
+ state->application_gain_map, state->auxiliary_gain_map,
+ auxiliary_samples, state, profile_state->calibration_ready,
+ GOODIX_MILAN_SENSOR_ROWS, GOODIX_MILAN_SENSOR_COLUMNS, gain,
+ working, optional_plane0) != 0)
+ goto out;
+ }
+ else
+ {
+ /* Native quirk: rejection suppresses map evolution, not persisted gain. */
+ profile9_update_source (normalized_live, setup_map, count, working);
+ for (size_t i = 0; i < count; i++)
+ {
+ uint32_t combined_gain = goodix_milan_profile9_combine_gain (
+ MILAN_FIXED_ONE, state->application_gain_map[i],
+ state->auxiliary_gain_map[i], profile_state->calibration_ready);
+ uint32_t secondary_divisor =
+ state->sample_count <= 3 || profile_state->calibration_ready != 0
+ ? MILAN_FIXED_ONE
+ : state->secondary_auxiliary_gain_map[i];
+
+ gain[i] = (uint16_t) combined_gain;
+ if (state->calibration_map[i] != 0)
+ {
+ optional_plane0[i] = secondary_divisor == 0
+ ? (uint16_t) ((uint32_t) working[i] << 14)
+ : (uint16_t) (((uint32_t) working[i] *
+ (MILAN_FIXED_ONE * 2) +
+ secondary_divisor / 2) /
+ secondary_divisor);
+ working[i] = combined_gain == 0
+ ? (uint16_t) ((uint32_t) working[i] << 14)
+ : (uint16_t) (((uint32_t) working[i] *
+ (MILAN_FIXED_ONE * 2) +
+ combined_gain / 2) /
+ combined_gain);
+ }
+ else
+ optional_plane0[i] = working[i];
+ }
+ }
+ for (size_t i = 0; i < count; i++)
+ refined_pixels += contrast_mask[i] != 0;
+ refined_percent = (uint16_t) (refined_pixels * 100 / count);
+
+ if (goodix_milan_preprocess_contrast (
+ working, contrast_mask, GOODIX_MILAN_SENSOR_ROWS,
+ GOODIX_MILAN_SENSOR_COLUMNS, contrast) != 0 ||
+ goodix_milan_preprocess_selection_mask (
+ contrast, GOODIX_MILAN_SENSOR_ROWS, GOODIX_MILAN_SENSOR_COLUMNS,
+ selection_mask) != 0 ||
+ preprocess_refine_core (
+ working, contrast_mask, refined_percent, GOODIX_MILAN_SENSOR_ROWS,
+ GOODIX_MILAN_SENSOR_COLUMNS, refined_source, refined) != 0 ||
+ goodix_milan_preprocess_select_output (
+ contrast, refined, selection_mask, GOODIX_MILAN_SENSOR_ROWS,
+ GOODIX_MILAN_SENSOR_COLUMNS, 800, output, &selected_refined) != 0)
+ goto out;
+ post_status = milan_profile9_post_render (
+ state, normalized_live, setup_map, contrast_mask, working,
+ optional_plane0, reciprocal_plane, output, selection_mask,
+ selected_refined, purpose,
+ &profile_state->calibration_ready, &first_metadata_mask,
+ &first_metadata_owned_mask,
+ &first_metadata_mode, &first_metadata_apply);
+ if (post_status < 0)
+ goto out;
+ /* The quality arm republishes the selected candidate before metadata. */
+ if (state->post_render.quality_gate && selected_refined)
+ memcpy (contrast, output, count);
+ milan_profile9_encode_metadata (
+ output, first_metadata_mask, GOODIX_MILAN_SENSOR_ROWS,
+ GOODIX_MILAN_SENSOR_COLUMNS, first_metadata_mode, first_metadata_apply);
+ free (first_metadata_owned_mask);
+ first_metadata_owned_mask = NULL;
+ classification_status = goodix_milan_profile9_build_broken_mask (
+ state, difference, setup_map, normalized_live, contrast_mask,
+ GOODIX_MILAN_SENSOR_ROWS, GOODIX_MILAN_SENSOR_COLUMNS, broken_mask,
+ NULL, &metadata_mode, &apply_metadata_mask);
+ if (classification_status != 0 &&
+ classification_status != GOODIX_MILAN_PREPROCESS_RETRY_CLASSIFICATION)
+ goto out;
+ milan_profile9_encode_metadata (
+ output, broken_mask, GOODIX_MILAN_SENSOR_ROWS,
+ GOODIX_MILAN_SENSOR_COLUMNS, metadata_mode, apply_metadata_mask);
+ if (
+ goodix_milan_preprocess_quality (
+ output, GOODIX_MILAN_SENSOR_ROWS, GOODIX_MILAN_SENSOR_COLUMNS,
+ quality, coverage) != 0)
+ goto out;
+ if (*coverage <= 5)
+ *quality = 0;
+ memcpy (state->setup_map, setup_map, count * sizeof(*setup_map));
+ memcpy (state->primary_contrast, selected_refined ? contrast : output, count);
+ state->primary_contrast_valid = 1;
+ state->selected_refined = selected_refined;
+ result = classification_status == GOODIX_MILAN_PREPROCESS_RETRY_CLASSIFICATION
+ ? classification_status : post_status;
+
+out:
+ free (first_metadata_owned_mask);
+ free (selection_mask);
+ free (contrast_mask);
+ free (broken_mask);
+ free (refined);
+ free (contrast);
+ free (mask);
+ free (reciprocal_plane);
+ free (optional_plane0);
+ free (refined_source);
+ free (working);
+ free (gain);
+ free (difference);
+ free (normalized_live);
+ free (setup_map);
+ return result;
+}
+
+static int
+is_invalid_border_sample (uint16_t sample)
+{
+ return sample == 0 || sample == MILAN_ADC_MAX;
+}
+
+int
+goodix_milan_preprocess_clamp_and_admit_raw (uint16_t *frame,
+ size_t rows,
+ size_t columns,
+ size_t border,
+ unsigned required_percent)
+{
+ size_t samples = 0;
+ size_t admitted = 0;
+
+ if (!frame || required_percent > 100 || border > rows / 2 ||
+ border > columns / 2 || rows - border <= border ||
+ columns - border <= border || columns > SIZE_MAX / rows)
+ return 0;
+
+ for (size_t i = 0; i < rows * columns; i++)
+ if (frame[i] > MILAN_ADC_MAX)
+ frame[i] = MILAN_ADC_MAX;
+ for (size_t row = border; row < rows - border; row++)
+ for (size_t column = border; column < columns - border; column++)
+ {
+ uint16_t sample = frame[row * columns + column];
+
+ samples++;
+ admitted += sample > MILAN_PROFILE9_RAW_ADMISSION_SAMPLE_MIN_EXCLUSIVE &&
+ sample < MILAN_PROFILE9_RAW_ADMISSION_SAMPLE_MAX_EXCLUSIVE;
+ }
+ return admitted > (samples / 100) * required_percent +
+ ((samples % 100) * required_percent) / 100;
+}
+
+int
+goodix_milan_preprocess_normalize (uint16_t *frame,
+ size_t rows,
+ size_t columns)
+{
+ size_t count;
+
+ if (!frame || rows < 4 || columns < 4 || columns > SIZE_MAX / rows)
+ return -1;
+
+ count = rows * columns;
+ for (size_t i = 0; i < count; i++)
+ {
+ if (frame[i] > MILAN_ADC_MAX)
+ frame[i] = MILAN_ADC_MAX;
+ }
+
+ for (size_t column = 1; column < columns - 1; column++)
+ {
+ size_t top_inner = columns + column;
+ size_t bottom_inner = (rows - 2) * columns + column;
+
+ if (is_invalid_border_sample (frame[top_inner]))
+ frame[top_inner] = frame[top_inner + columns];
+ if (is_invalid_border_sample (frame[bottom_inner]))
+ frame[bottom_inner] = frame[bottom_inner - columns];
+
+ frame[column] = frame[top_inner];
+ frame[(rows - 1) * columns + column] = frame[bottom_inner];
+ }
+
+ for (size_t row = 0; row < rows; row++)
+ {
+ size_t start = row * columns;
+
+ if (is_invalid_border_sample (frame[start + 1]))
+ frame[start + 1] = frame[start + 2];
+ if (is_invalid_border_sample (frame[start + columns - 2]))
+ frame[start + columns - 2] = frame[start + columns - 3];
+
+ frame[start] = frame[start + 1];
+ frame[start + columns - 1] = frame[start + columns - 2];
+ }
+
+ return 0;
+}
+
+static int
+profile9_normalize_outer_edges (uint16_t *frame,
+ size_t rows,
+ size_t columns)
+{
+ size_t count;
+
+ if (rows < 3 || columns < 2 || columns > SIZE_MAX / rows)
+ return -1;
+
+ count = rows * columns;
+ for (size_t i = 0; i < count; i++)
+ if (frame[i] > MILAN_ADC_MAX)
+ frame[i] = MILAN_ADC_MAX;
+
+ /* Native quirk: validated frames copy outer edges but preserve inner edges. */
+ memcpy (frame, frame + columns, columns * sizeof(*frame));
+ memcpy (frame + (rows - 1) * columns, frame + (rows - 2) * columns,
+ columns * sizeof(*frame));
+ for (size_t row = 0; row < rows; row++)
+ {
+ size_t start = row * columns;
+
+ frame[start] = frame[start + 1];
+ frame[start + columns - 1] = frame[start + columns - 2];
+ }
+
+ return 0;
+}
+
+int
+goodix_milan_preprocess_make_setup_map (const uint16_t *frame,
+ size_t rows,
+ size_t columns,
+ uint16_t *setup_map,
+ uint32_t *rounded_mean)
+{
+ size_t count;
+ uint64_t count64;
+ uint64_t sum = 0;
+
+ if (columns == 0 || rows > SIZE_MAX / columns)
+ return -1;
+
+ count = rows * columns;
+ if (count > SIZE_MAX / sizeof(*setup_map))
+ return -1;
+ count64 = count;
+ if (count64 > (UINT64_MAX - count64 / 2) / MILAN_ADC_MAX)
+ return -1;
+
+ memmove (setup_map, frame, count * sizeof(*setup_map));
+ if (profile9_normalize_outer_edges (setup_map, rows, columns) != 0)
+ return -1;
+
+ for (size_t i = 0; i < count; i++)
+ sum += setup_map[i];
+
+ *rounded_mean = (uint32_t) ((sum + count64 / 2) / count64);
+ for (size_t i = 0; i < count; i++)
+ setup_map[i] += MILAN_PROFILE9_SETUP_OFFSET;
+ return 0;
+}
+
+int
+goodix_milan_preprocess_build_mask (const uint16_t *normalized_live,
+ const uint16_t *setup_map,
+ size_t rows,
+ size_t columns,
+ uint8_t *mask,
+ uint16_t *threshold,
+ uint16_t *valid_percent)
+{
+ size_t count;
+ int difference_count = 0;
+ int difference_sum = 0;
+ int invalid_count = 0;
+ int selected_threshold = 50;
+
+ if (rows == 0 || columns == 0 ||
+ columns > SIZE_MAX / rows)
+ return -1;
+
+ count = rows * columns;
+ if (count > INT16_MAX || columns > INT_MAX / 10)
+ return -1;
+
+ for (size_t i = 0; i < count; i++)
+ {
+ int difference = (int) setup_map[i] - (int) normalized_live[i];
+
+ if (difference > 50)
+ {
+ difference_count++;
+ difference_sum += difference;
+ }
+ }
+
+ if (difference_count > 0)
+ {
+ int learned_threshold = (difference_sum / difference_count) / 5;
+
+ if (difference_count > (int) columns * 10 ||
+ learned_threshold > selected_threshold)
+ selected_threshold = learned_threshold;
+ }
+
+ for (size_t i = 0; i < count; i++)
+ {
+ int difference = (int) setup_map[i] - (int) normalized_live[i];
+ int valid = 1;
+
+ if (difference < selected_threshold)
+ {
+ valid = 0;
+ invalid_count++;
+ }
+ if (normalized_live[i] == MILAN_ADC_MAX)
+ {
+ valid = 0;
+ invalid_count++;
+ }
+
+ mask[i] = valid ? UINT8_MAX : 0;
+ }
+
+ *threshold = (uint16_t) selected_threshold;
+ *valid_percent =
+ (uint16_t) (((int) count - invalid_count) * 100 / (int) count);
+ return 0;
+}
+
+int
+goodix_milan_preprocess_no_update_frame (const uint16_t *normalized_live,
+ const uint16_t *setup_map,
+ size_t rows,
+ size_t columns,
+ uint16_t *output)
+{
+ size_t count;
+
+ if (rows != 0 && columns > SIZE_MAX / rows)
+ return -1;
+
+ count = rows * columns;
+ for (size_t i = 0; i < count; i++)
+ output[i] = setup_map[i] > normalized_live[i]
+ ? setup_map[i] - normalized_live[i]
+ : 0;
+
+ return 0;
+}
+
+static void
+update_gaussian_core (const uint16_t *source,
+ size_t rows,
+ size_t columns,
+ uint16_t *horizontal,
+ uint16_t *output)
+{
+ for (size_t row = 0; row < rows; row++)
+ {
+ for (size_t column = 0; column < columns; column++)
+ {
+ uint64_t sum = 0;
+
+ for (size_t tap = 0; tap < 5; tap++)
+ {
+ size_t x = goodix_milan_reflect101_index (
+ (ptrdiff_t) column + (ptrdiff_t) tap - 2, columns);
+
+ sum += (uint64_t) source[row * columns + x] *
+ milan_update_kernel[tap];
+ }
+ horizontal[row * columns + column] = (uint16_t) (sum >> 16);
+ }
+ }
+
+ for (size_t row = 0; row < rows; row++)
+ {
+ for (size_t column = 0; column < columns; column++)
+ {
+ uint64_t sum = 0;
+
+ for (size_t tap = 0; tap < 5; tap++)
+ {
+ size_t y = goodix_milan_reflect101_index (
+ (ptrdiff_t) row + (ptrdiff_t) tap - 2, rows);
+
+ sum += (uint64_t) horizontal[y * columns + column] *
+ milan_update_kernel[tap];
+ }
+ output[row * columns + column] = (uint16_t) (sum >> 16);
+ }
+ }
+}
+
+static uint16_t
+median3 (uint16_t a,
+ uint16_t b,
+ uint16_t c)
+{
+ uint16_t lower = a < b ? a : b;
+ uint16_t upper = a > b ? a : b;
+ uint16_t capped = upper < c ? upper : c;
+
+ return lower > capped ? lower : capped;
+}
+
+static void
+median3x3_core (const uint16_t *source,
+ size_t rows,
+ size_t columns,
+ uint16_t *output)
+{
+ memcpy (output, source, rows * columns * sizeof(*source));
+ for (size_t row = 1; row + 1 < rows; row++)
+ {
+ for (size_t column = 1; column + 1 < columns; column++)
+ {
+ uint16_t row_medians[3];
+
+ for (ptrdiff_t row_offset = -1; row_offset <= 1; row_offset++)
+ {
+ size_t index = (row + row_offset) * columns + column;
+
+ row_medians[row_offset + 1] =
+ median3 (source[index - 1], source[index], source[index + 1]);
+ }
+
+ output[row * columns + column] =
+ median3 (row_medians[0], row_medians[1], row_medians[2]);
+ }
+ }
+}
+
+static int
+profile9_calibration_admit (const uint16_t *source,
+ size_t rows,
+ size_t columns,
+ GoodixMilanPreprocessState *state)
+{
+ size_t coarse_rows = rows / 2;
+ size_t coarse_columns = columns / 2;
+ int refresh_reference = state->auxiliary_sample_count == 0;
+
+ if (state->auxiliary_sample_count != 0)
+ {
+ uint64_t difference_sum = 0;
+
+ for (size_t row = 0; row < coarse_rows; row++)
+ for (size_t column = 0; column < coarse_columns; column++)
+ {
+ uint16_t current =
+ source[(row * 2) * columns + column * 2];
+ uint16_t previous =
+ state->coarse_reference[row * coarse_columns + column];
+
+ difference_sum += current > previous ? current - previous
+ : previous - current;
+ }
+
+ if (difference_sum / (coarse_rows * coarse_columns) < 30)
+ state->stable_count++;
+ else
+ {
+ state->stable_count = 0;
+ refresh_reference = 1;
+ }
+ }
+ else
+ {
+ state->stable_count = 0;
+ }
+
+ if (refresh_reference)
+ for (size_t row = 0; row < coarse_rows; row++)
+ for (size_t column = 0; column < coarse_columns; column++)
+ state->coarse_reference[row * coarse_columns + column] =
+ source[(row * 2) * columns + column * 2];
+
+ /* Native increments a wrapping dword, then compares it as signed. */
+ if ((int32_t) state->stable_count > 3)
+ return 0;
+
+ return 1;
+}
+
+static void
+profile9_update_calibration (const uint32_t *ratio,
+ size_t count,
+ GoodixMilanPreprocessState *state)
+{
+ uint32_t sum = 0;
+ uint32_t map_sum = 0;
+ uint32_t mean;
+ uint32_t scale;
+
+ for (size_t i = 0; i < count; i++)
+ sum += ratio[i];
+ mean = (sum + count / 2) / count;
+ if (mean == 0)
+ mean = 8000;
+ scale = (UINT32_C(8000) * MILAN_FIXED_ONE + mean / 2) / mean;
+
+ for (size_t i = 0; i < count; i++)
+ {
+ uint32_t candidate =
+ (uint32_t) (((uint64_t) ratio[i] * scale + MILAN_FIXED_ONE / 2) /
+ MILAN_FIXED_ONE);
+ int32_t deviation = (int32_t) candidate - 8000;
+
+ if (deviation < 0)
+ deviation = -deviation;
+ if (deviation < 6400)
+ {
+ uint32_t divisor = state->sample_count + 1;
+
+ state->calibration_map[i] =
+ (uint16_t) (((divisor >> 1) +
+ (uint32_t) state->calibration_map[i] *
+ state->sample_count + candidate) /
+ divisor);
+ }
+ map_sum += state->calibration_map[i];
+ }
+
+ state->sample_count++;
+ if (state->sample_count > 400)
+ state->sample_count = 400;
+
+ if (state->sample_count > 3)
+ {
+ uint32_t map_mean = (map_sum + count / 2) / count;
+
+ if (map_mean != 0)
+ for (size_t i = 0; i < count; i++)
+ state->application_gain_map[i] =
+ (uint16_t) (((uint32_t) state->calibration_map[i] *
+ MILAN_FIXED_ONE + map_mean / 2) /
+ map_mean);
+ }
+
+}
+
+static void
+profile9_update_source (const uint16_t *normalized_live,
+ const uint16_t *setup_map,
+ size_t count,
+ uint16_t *output)
+{
+ for (size_t i = 0; i < count; i++)
+ {
+ uint16_t normalized_setup =
+ setup_map[i] >= MILAN_PROFILE9_SETUP_OFFSET
+ ? setup_map[i] - MILAN_PROFILE9_SETUP_OFFSET
+ : 0;
+ int32_t value =
+ MILAN_PROFILE9_UPDATE_BASE +
+ 3 * ((int32_t) normalized_setup - (int32_t) normalized_live[i]);
+
+ output[i] = (uint16_t) (value <= 0
+ ? 0
+ : value <= UINT16_MAX ? value : UINT16_MAX);
+ }
+}
+
+static void
+profile9_update_auxiliary_map (uint16_t *map,
+ uint32_t samples,
+ const uint16_t *adjusted,
+ const uint16_t *gaussian,
+ size_t count)
+{
+ for (size_t i = 0; i < count; i++)
+ {
+ uint16_t candidate = MILAN_FIXED_ONE;
+ int32_t deviation;
+
+ if (gaussian[i] != 0)
+ candidate =
+ ((uint32_t) adjusted[i] * MILAN_FIXED_ONE + gaussian[i] / 2) /
+ gaussian[i];
+ deviation = (int32_t) candidate - (int32_t) MILAN_FIXED_ONE;
+
+ if (deviation < 0)
+ deviation = -deviation;
+ if (deviation < 328)
+ {
+ uint32_t divisor = samples + 1;
+
+ map[i] =
+ (uint16_t) (((divisor >> 1) + (uint32_t) map[i] * samples +
+ candidate) /
+ divisor);
+ }
+ }
+}
+
+static void
+profile9_build_temporary_gain (const uint16_t *difference,
+ const uint16_t *median,
+ size_t count,
+ uint16_t *gain_map,
+ uint32_t *ratio,
+ uint16_t *adjusted)
+{
+ for (size_t i = 0; i < count; i++)
+ {
+ uint32_t gain = MILAN_FIXED_ONE;
+
+ if (difference[i] != 0 && median[i] != 0)
+ {
+ int32_t deviation = (int32_t) difference[i] - (int32_t) median[i];
+
+ if (deviation < 0)
+ deviation = -deviation;
+ if (deviation > 1800)
+ gain = ((uint32_t) difference[i] * MILAN_FIXED_ONE +
+ median[i] / 2) /
+ median[i];
+ if (gain > INT16_MAX)
+ gain = INT16_MAX;
+ }
+
+ gain_map[i] = (uint16_t) gain;
+ ratio[i] = gain != 0 ?
+ ((uint32_t) difference[i] * MILAN_FIXED_ONE + gain / 2) /
+ gain :
+ (uint32_t) difference[i] << 13;
+ adjusted[i] = (uint16_t) ratio[i];
+ }
+}
+
+static void
+profile9_update_calibration_state (
+ const uint16_t *difference,
+ const uint32_t *ratio,
+ const uint16_t *adjusted,
+ const uint16_t *gaussian,
+ const uint16_t *application_gain_map,
+ uint32_t calibration_ready,
+ size_t rows,
+ size_t columns,
+ uint16_t *horizontal_scratch,
+ uint16_t *gain_map,
+ uint16_t *optional_plane0,
+ uint16_t *application_adjusted,
+ uint16_t *application_gaussian,
+ GoodixMilanPreprocessState *state)
+{
+ size_t count = rows * columns;
+ int calibration_admitted =
+ profile9_calibration_admit (difference, rows, columns, state);
+
+ if (calibration_admitted)
+ {
+ for (size_t i = 0; i < count; i++)
+ {
+ uint32_t combined_gain =
+ ((uint32_t) gain_map[i] * application_gain_map[i] + 0x1000) >> 13;
+ uint32_t value =
+ combined_gain != 0 ?
+ ((uint32_t) difference[i] * MILAN_FIXED_ONE +
+ combined_gain / 2) /
+ combined_gain :
+ (uint32_t) difference[i] << 13;
+
+ application_adjusted[i] = (uint16_t) value;
+ }
+ update_gaussian_core (application_adjusted, rows, columns,
+ horizontal_scratch, application_gaussian);
+ profile9_update_auxiliary_map (
+ state->auxiliary_gain_map, state->auxiliary_sample_count,
+ application_adjusted, application_gaussian, count);
+ profile9_update_auxiliary_map (
+ state->secondary_auxiliary_gain_map, state->auxiliary_sample_count,
+ adjusted, gaussian, count);
+ if (state->auxiliary_sample_count < 30)
+ state->auxiliary_sample_count++;
+ state->update_state = 1;
+ }
+ if (optional_plane0)
+ {
+ for (size_t i = 0; i < count; i++)
+ optional_plane0[i] =
+ state->sample_count <= 3 || calibration_ready != 0 ?
+ gain_map[i] :
+ (uint16_t) (((uint32_t) gain_map[i] *
+ state->secondary_auxiliary_gain_map[i] +
+ MILAN_FIXED_ONE / 2) >>
+ 13);
+ }
+ for (size_t i = 0; i < count; i++)
+ gain_map[i] = goodix_milan_profile9_combine_gain (
+ gain_map[i], application_gain_map[i], state->auxiliary_gain_map[i],
+ calibration_ready);
+ if (calibration_admitted)
+ profile9_update_calibration (ratio, count, state);
+}
+
+static void
+profile9_update_stateless_gain (const uint16_t *adjusted,
+ const uint16_t *gaussian,
+ uint32_t auxiliary_samples,
+ size_t count,
+ uint16_t *persistent_auxiliary_gain,
+ uint16_t *gain_map,
+ uint16_t *optional_plane0)
+{
+ if (persistent_auxiliary_gain)
+ profile9_update_auxiliary_map (persistent_auxiliary_gain,
+ auxiliary_samples, adjusted, gaussian,
+ count);
+ for (size_t i = 0; i < count; i++)
+ {
+ uint32_t auxiliary_gain = MILAN_FIXED_ONE;
+
+ if (persistent_auxiliary_gain)
+ {
+ auxiliary_gain = persistent_auxiliary_gain[i];
+ }
+ else if (gaussian[i] != 0)
+ {
+ uint32_t candidate =
+ ((uint32_t) adjusted[i] * MILAN_FIXED_ONE + gaussian[i] / 2) /
+ gaussian[i];
+ int32_t deviation =
+ (int32_t) candidate - (int32_t) MILAN_FIXED_ONE;
+
+ if (deviation < 0)
+ deviation = -deviation;
+ if (deviation < 328)
+ auxiliary_gain = candidate;
+ }
+
+ gain_map[i] =
+ (uint16_t) (((uint32_t) gain_map[i] * auxiliary_gain + 0x1000) >> 13);
+ if (optional_plane0)
+ optional_plane0[i] = gain_map[i];
+ }
+}
+
+static void
+profile9_render_update_source (const uint16_t *difference,
+ const uint16_t *application_map,
+ const uint16_t *gain_map,
+ size_t count,
+ uint16_t *output,
+ uint16_t *optional_plane0)
+{
+ for (size_t i = 0; i < count; i++)
+ {
+ uint16_t secondary_divisor = optional_plane0 ? optional_plane0[i] : 0;
+
+ if (application_map && application_map[i] == 0)
+ {
+ output[i] = difference[i];
+ if (optional_plane0)
+ optional_plane0[i] = difference[i];
+ }
+ else
+ {
+ output[i] = gain_map[i] == 0 ?
+ (uint16_t) ((uint32_t) difference[i] << 14) :
+ (uint16_t) (((uint32_t) difference[i] *
+ (MILAN_FIXED_ONE * 2) +
+ gain_map[i] / 2) /
+ gain_map[i]);
+ if (optional_plane0)
+ {
+ optional_plane0[i] =
+ secondary_divisor == 0 ?
+ (uint16_t) ((uint32_t) difference[i] << 14) :
+ (uint16_t) (((uint32_t) difference[i] *
+ (MILAN_FIXED_ONE * 2) +
+ secondary_divisor / 2) /
+ secondary_divisor);
+ }
+ }
+ }
+}
+
+static int
+first_update_frame_core (const uint16_t *normalized_live,
+ const uint16_t *setup_map,
+ const uint16_t *application_map,
+ const uint16_t *application_gain_map,
+ uint16_t *persistent_auxiliary_gain,
+ uint32_t auxiliary_samples,
+ GoodixMilanPreprocessState *state,
+ uint32_t calibration_ready,
+ size_t rows,
+ size_t columns,
+ uint16_t *gain_map,
+ uint16_t *output,
+ uint16_t *optional_plane0)
+{
+ size_t count;
+ uint32_t *ratio = NULL;
+ uint16_t *adjusted = NULL;
+ uint16_t *application_adjusted = NULL;
+ uint16_t *difference = NULL;
+ uint16_t *gaussian = NULL;
+ uint16_t *application_gaussian = NULL;
+ uint16_t *median = NULL;
+
+ if (gain_map == output || optional_plane0 == gain_map ||
+ optional_plane0 == output ||
+ rows > PTRDIFF_MAX || columns > PTRDIFF_MAX ||
+ (rows != 0 && columns > SIZE_MAX / rows))
+ return -1;
+
+ count = rows * columns;
+ if (count > SIZE_MAX / sizeof(uint16_t))
+ return -1;
+
+ ratio = malloc (count * sizeof(*ratio));
+ adjusted = malloc (count * sizeof(*adjusted));
+ application_adjusted = state
+ ? malloc (count * sizeof(*application_adjusted))
+ : NULL;
+ difference = calloc (count, sizeof(*difference));
+ gaussian = malloc (count * sizeof(*gaussian));
+ application_gaussian = state
+ ? malloc (count * sizeof(*application_gaussian))
+ : NULL;
+ median = malloc (count * sizeof(*median));
+ if (!ratio || !adjusted || (state && !application_adjusted) || !difference ||
+ !gaussian || (state && !application_gaussian) || !median)
+ goto allocation_failed;
+
+ profile9_update_source (normalized_live, setup_map, count, difference);
+
+ median3x3_core (difference, rows, columns, median);
+ profile9_build_temporary_gain (
+ difference, median, count, gain_map, ratio, adjusted);
+
+ update_gaussian_core (adjusted, rows, columns, output, gaussian);
+ if (state)
+ {
+ profile9_update_calibration_state (
+ difference, ratio, adjusted, gaussian, application_gain_map,
+ calibration_ready, rows, columns, output, gain_map, optional_plane0,
+ application_adjusted, application_gaussian, state);
+ }
+ else
+ {
+ profile9_update_stateless_gain (
+ adjusted, gaussian, auxiliary_samples, count, persistent_auxiliary_gain,
+ gain_map, optional_plane0);
+ }
+
+ profile9_render_update_source (
+ difference, application_map, gain_map, count, output, optional_plane0);
+
+ free (median);
+ free (application_gaussian);
+ free (gaussian);
+ free (difference);
+ free (application_adjusted);
+ free (adjusted);
+ free (ratio);
+ return 0;
+
+allocation_failed:
+ free (median);
+ free (application_gaussian);
+ free (gaussian);
+ free (difference);
+ free (application_adjusted);
+ free (adjusted);
+ free (ratio);
+ return -1;
+}
+
+static int
+preprocess_refine_core (const uint16_t *source,
+ const uint8_t *mask,
+ uint16_t valid_percent,
+ size_t rows,
+ size_t columns,
+ uint16_t *centered,
+ uint8_t *output)
+{
+ for (size_t row = 0; row < rows; row++)
+ {
+ uint32_t sum = 0;
+ size_t contributors = 0;
+ size_t start = row * columns;
+
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t index = start + column;
+
+ if (valid_percent >= 96 || mask[index] != 0)
+ {
+ sum += source[index];
+ contributors++;
+ }
+ }
+
+ uint16_t mean = contributors != 0 ? (uint16_t) (sum / contributors) : 0;
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t index = start + column;
+ int value;
+
+ if (valid_percent < 96 && mask[index] == 0)
+ value = 5000;
+ else
+ value = (int16_t) ((int) source[index] - mean + 5000);
+ centered[index] = (uint16_t) (value > 0 ? value : 0);
+ }
+ }
+
+ return goodix_milan_preprocess_contrast (
+ centered, mask, rows, columns, output);
+}
+
+int
+goodix_milan_preprocess_refine (const uint16_t *source,
+ const uint8_t *mask,
+ uint16_t valid_percent,
+ size_t rows,
+ size_t columns,
+ uint8_t *output)
+{
+ size_t count;
+ uint16_t *centered;
+ int result;
+
+ if (!source || !mask || !output || rows == 0 || columns == 0 ||
+ columns > SIZE_MAX / rows)
+ return -1;
+ count = rows * columns;
+ if (count > SIZE_MAX / sizeof(*centered))
+ return -1;
+ centered = malloc (count * sizeof(*centered));
+ if (!centered)
+ return -1;
+ result = preprocess_refine_core (
+ source, mask, valid_percent, rows, columns, centered, output);
+ free (centered);
+ return result;
+}
+
+static int
+quality_combine_core (int raw_coverage,
+ int valid_score,
+ int patch_score,
+ int mask_fraction,
+ int fraction_cutoff,
+ int final_adjustment,
+ int positive_only_adjustment,
+ int *quality,
+ int *coverage)
+{
+ int result;
+
+ if (!quality || !coverage || raw_coverage < 0 || valid_score < 0 ||
+ patch_score < 0 || mask_fraction < 0)
+ return -1;
+
+ result = patch_score;
+ if (mask_fraction < fraction_cutoff &&
+ patch_score < MILAN_QUALITY_PATCH_REDUCTION_CEILING)
+ {
+ int factor = mask_fraction * MILAN_QUALITY_Q8_ONE / fraction_cutoff;
+
+ result = result * factor >> MILAN_QUALITY_Q8_SHIFT;
+ result = result * factor >> MILAN_QUALITY_Q8_SHIFT;
+ }
+
+ if (valid_score - raw_coverage > MILAN_QUALITY_VALID_COVERAGE_DELTA &&
+ valid_score != 0)
+ {
+ result = raw_coverage * result / valid_score;
+ result = result * raw_coverage / valid_score;
+ }
+
+ if (!positive_only_adjustment || result > 0)
+ result += final_adjustment;
+ if (result < 0)
+ result = 0;
+ else if (result > MILAN_QUALITY_PERCENT_SCALE)
+ result = MILAN_QUALITY_PERCENT_SCALE;
+
+ *quality = result;
+ *coverage = raw_coverage * MILAN_QUALITY_PERCENT_SCALE >>
+ MILAN_QUALITY_Q16_SHIFT;
+ return 0;
+}
+
+static void
+quality_gaussian_reflect101 (const uint8_t *source,
+ size_t rows,
+ size_t columns,
+ const uint16_t *kernel,
+ size_t kernel_width,
+ uint16_t *horizontal,
+ uint8_t *output)
+{
+ ptrdiff_t radius = (ptrdiff_t) (kernel_width / 2);
+
+ for (size_t row = 0; row < rows; row++)
+ {
+ for (size_t column = 0; column < columns; column++)
+ {
+ uint64_t sum = 0;
+
+ for (size_t tap = 0; tap < kernel_width; tap++)
+ {
+ size_t x = goodix_milan_reflect101_index (
+ (ptrdiff_t) column + (ptrdiff_t) tap - radius, columns);
+
+ sum += ((uint64_t) source[row * columns + x] << 8) *
+ kernel[tap];
+ }
+ horizontal[row * columns + column] = (uint16_t) (sum >> 16);
+ }
+ }
+
+ for (size_t row = 0; row < rows; row++)
+ {
+ for (size_t column = 0; column < columns; column++)
+ {
+ uint64_t sum = 0;
+
+ for (size_t tap = 0; tap < kernel_width; tap++)
+ {
+ size_t y = goodix_milan_reflect101_index (
+ (ptrdiff_t) row + (ptrdiff_t) tap - radius, rows);
+
+ sum += (uint64_t) horizontal[y * columns + column] *
+ kernel[tap];
+ }
+ output[row * columns + column] = (uint8_t) ((sum >> 16) >> 8);
+ }
+ }
+}
+
+static void
+quality_sobel_half_l1 (const uint8_t *source,
+ size_t rows,
+ size_t columns,
+ int16_t *sobel_x,
+ int16_t *sobel_y,
+ uint16_t *gradient)
+{
+ for (size_t row = 0; row < rows; row++)
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t index = row * columns + column;
+
+ if (column == 0 || column + 1 == columns)
+ {
+ sobel_x[index] = 0;
+ }
+ else
+ {
+ size_t previous_row =
+ goodix_milan_reflect101_index ((ptrdiff_t) row - 1, rows);
+ size_t next_row =
+ goodix_milan_reflect101_index ((ptrdiff_t) row + 1, rows);
+ int previous = source[previous_row * columns + column + 1] -
+ source[previous_row * columns + column - 1];
+ int current = source[row * columns + column + 1] -
+ source[row * columns + column - 1];
+ int next = source[next_row * columns + column + 1] -
+ source[next_row * columns + column - 1];
+
+ sobel_x[index] = (int16_t) (previous + current * 2 + next);
+ }
+ if (row == 0 || row + 1 == rows)
+ {
+ sobel_y[index] = 0;
+ }
+ else
+ {
+ size_t previous_column = goodix_milan_reflect101_index (
+ (ptrdiff_t) column - 1, columns);
+ size_t next_column = goodix_milan_reflect101_index (
+ (ptrdiff_t) column + 1, columns);
+ int previous = source[(row + 1) * columns + previous_column] -
+ source[(row - 1) * columns + previous_column];
+ int current = source[(row + 1) * columns + column] -
+ source[(row - 1) * columns + column];
+ int next = source[(row + 1) * columns + next_column] -
+ source[(row - 1) * columns + next_column];
+
+ sobel_y[index] = (int16_t) (previous + current * 2 + next);
+ }
+
+ int x = sobel_x[index];
+ int y = sobel_y[index];
+ gradient[index] = (uint16_t) ((x < 0 ? -x : x) / 2 +
+ (y < 0 ? -y : y) / 2);
+ }
+}
+
+static size_t
+quality_threshold_gradient_window (const uint16_t *gradient,
+ size_t rows,
+ size_t columns,
+ uint16_t threshold,
+ uint8_t mask_value,
+ uint8_t *mask)
+{
+ size_t selected = 0;
+
+ for (size_t row = 0; row < rows; row++)
+ {
+ uint32_t sum = 0;
+
+ for (ptrdiff_t y_offset = -7; y_offset <= 7; y_offset++)
+ {
+ size_t y = goodix_milan_reflect101_index (
+ (ptrdiff_t) row + y_offset, rows);
+
+ for (ptrdiff_t x_offset = -7; x_offset <= 7; x_offset++)
+ {
+ size_t x = goodix_milan_reflect101_index (x_offset, columns);
+
+ sum += gradient[y * columns + x];
+ }
+ }
+ for (size_t column = 0; column < columns; column++)
+ {
+ uint16_t average = (uint16_t) (
+ (sum * (uint32_t) MILAN_QUALITY_GRADIENT_WINDOW_RECIPROCAL_Q16) >>
+ MILAN_QUALITY_Q16_SHIFT);
+ size_t index = row * columns + column;
+
+ mask[index] = average > threshold ? mask_value : 0;
+ selected += mask[index] != 0;
+ if (column + 1 < columns)
+ {
+ size_t leaving = goodix_milan_reflect101_index (
+ (ptrdiff_t) column - 7, columns);
+ size_t entering = goodix_milan_reflect101_index (
+ (ptrdiff_t) column + 8, columns);
+
+ /* Keep reflected samples with their original multiplicities. */
+ for (ptrdiff_t y_offset = -7; y_offset <= 7; y_offset++)
+ {
+ size_t y = goodix_milan_reflect101_index (
+ (ptrdiff_t) row + y_offset, rows);
+
+ sum -= gradient[y * columns + leaving];
+ sum += gradient[y * columns + entering];
+ }
+ }
+ }
+ }
+ return selected;
+}
+
+static int
+quality_coverage_mask_core (const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ uint16_t threshold,
+ uint8_t mask_value,
+ uint8_t *mask,
+ int *raw_coverage)
+{
+ size_t count;
+ uint16_t *horizontal = NULL;
+ uint8_t *blurred = NULL;
+ int16_t *sobel_x = NULL;
+ int16_t *sobel_y = NULL;
+ uint16_t *gradient = NULL;
+ size_t selected = 0;
+
+ if (!frame || !mask || !raw_coverage || rows < 2 || columns < 2 ||
+ rows > PTRDIFF_MAX || columns > PTRDIFF_MAX ||
+ columns > SIZE_MAX / rows)
+ return -1;
+
+ count = rows * columns;
+ if (count > INT_MAX || count > SIZE_MAX / sizeof(uint16_t))
+ return -1;
+
+ horizontal = malloc (count * sizeof(*horizontal));
+ blurred = malloc (count);
+ sobel_x = malloc (count * sizeof(*sobel_x));
+ sobel_y = malloc (count * sizeof(*sobel_y));
+ gradient = malloc (count * sizeof(*gradient));
+ if (!horizontal || !blurred || !sobel_x || !sobel_y || !gradient)
+ goto allocation_failed;
+
+ quality_gaussian_reflect101 (
+ frame, rows, columns, milan_quality_gaussian7_kernel,
+ sizeof (milan_quality_gaussian7_kernel) /
+ sizeof (milan_quality_gaussian7_kernel[0]),
+ horizontal, blurred);
+ quality_sobel_half_l1 (
+ blurred, rows, columns, sobel_x, sobel_y, gradient);
+ selected = quality_threshold_gradient_window (
+ gradient, rows, columns, threshold, mask_value, mask);
+
+ *raw_coverage = (int) ((selected * (uint32_t) MILAN_QUALITY_Q16_ONE) /
+ count);
+ free (gradient);
+ free (sobel_y);
+ free (sobel_x);
+ free (blurred);
+ free (horizontal);
+ return 0;
+
+allocation_failed:
+ free (gradient);
+ free (sobel_y);
+ free (sobel_x);
+ free (blurred);
+ free (horizontal);
+ return -1;
+}
+
+int
+goodix_milan_preprocess_quality_coverage_mask (const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ uint8_t *mask,
+ int *raw_coverage)
+{
+ return quality_coverage_mask_core (
+ frame, rows, columns, MILAN_QUALITY_COVERAGE_THRESHOLD, UINT8_MAX,
+ mask, raw_coverage);
+}
+
+int
+goodix_milan_preprocess_selection_mask (const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ uint8_t *mask)
+{
+ int ignored_coverage;
+
+ return quality_coverage_mask_core (
+ frame, rows, columns, MILAN_QUALITY_SELECTION_THRESHOLD, UINT8_MAX,
+ mask, &ignored_coverage);
+}
+
+static void
+quality_prepare_patch_gradients (const uint8_t *frame,
+ const uint8_t *valid_mask,
+ size_t rows,
+ size_t columns,
+ int32_t *gradient_x,
+ int32_t *gradient_y,
+ int32_t *magnitude)
+{
+ for (size_t row = 1; row + 1 < rows; row++)
+ for (size_t column = 1; column + 1 < columns; column++)
+ {
+ size_t index = row * columns + column;
+ int neighborhood_valid = 1;
+
+ for (ptrdiff_t y = -1; y <= 1 && neighborhood_valid; y++)
+ for (ptrdiff_t x = -1; x <= 1; x++)
+ if (valid_mask[(size_t) ((ptrdiff_t) row + y) * columns +
+ (size_t) ((ptrdiff_t) column + x)] == 0)
+ {
+ neighborhood_valid = 0;
+ break;
+ }
+ if (!neighborhood_valid)
+ continue;
+
+ int x = (int) frame[index + 1] - (int) frame[index - 1];
+ int y = (int) frame[index + columns] - (int) frame[index - columns];
+ gradient_x[index] = x;
+ gradient_y[index] = y;
+ magnitude[index] = x * x + y * y;
+ }
+}
+
+static void
+quality_rewrite_patch_mask (const int32_t *patch_scores,
+ const int score_histogram[],
+ int scored_patches,
+ size_t rows,
+ size_t columns,
+ size_t count,
+ uint8_t *refined_mask)
+{
+ int cumulative = 0;
+ int median_score = 0;
+
+ for (; median_score <= MILAN_QUALITY_PERCENT_SCALE; median_score++)
+ {
+ cumulative += score_histogram[median_score];
+ if (cumulative >= scored_patches / 2)
+ break;
+ }
+ for (size_t center_row = MILAN_QUALITY_PATCH_RADIUS;
+ center_row < rows - MILAN_QUALITY_PATCH_RADIUS;
+ center_row += MILAN_QUALITY_PATCH_STRIDE)
+ for (size_t center_column = MILAN_QUALITY_PATCH_RADIUS;
+ center_column < columns - MILAN_QUALITY_PATCH_RADIUS;
+ center_column += MILAN_QUALITY_PATCH_STRIDE)
+ {
+ size_t center = center_row * columns + center_column;
+ int32_t score = patch_scores[center];
+
+ if (score < 0 ||
+ ((score * MILAN_QUALITY_PERCENT_SCALE) >>
+ MILAN_QUALITY_Q16_SHIFT) > median_score)
+ continue;
+ for (size_t row = center_row - MILAN_QUALITY_PATCH_RADIUS;
+ row < center_row + MILAN_QUALITY_PATCH_RADIUS; row++)
+ for (size_t column = center_column - MILAN_QUALITY_PATCH_RADIUS;
+ column < center_column + MILAN_QUALITY_PATCH_RADIUS; column++)
+ {
+ size_t index = row * columns + column;
+
+ if (refined_mask[index] != 0)
+ refined_mask[index] = MILAN_QUALITY_REFINED_MASK_MARKER;
+ }
+ }
+ for (size_t i = 0; i < count; i++)
+ refined_mask[i] =
+ refined_mask[i] == MILAN_QUALITY_REFINED_MASK_MARKER ? UINT8_MAX : 0;
+}
+
+static void
+quality_accumulate_patch_scores (
+ const uint8_t *valid_mask,
+ const int32_t *gradient_x,
+ const int32_t *gradient_y,
+ const int32_t *magnitude,
+ size_t rows,
+ size_t columns,
+ int fixed_threshold,
+ int32_t *patch_scores,
+ int score_histogram[MILAN_QUALITY_SCORE_BIN_COUNT],
+ int64_t *score_sum,
+ int *scored_patches)
+{
+ for (size_t center_row = MILAN_QUALITY_PATCH_RADIUS;
+ center_row < rows - MILAN_QUALITY_PATCH_RADIUS;
+ center_row += MILAN_QUALITY_PATCH_STRIDE)
+ {
+ for (size_t center_column = MILAN_QUALITY_PATCH_RADIUS;
+ center_column < columns - MILAN_QUALITY_PATCH_RADIUS;
+ center_column += MILAN_QUALITY_PATCH_STRIDE)
+ {
+ size_t center = center_row * columns + center_column;
+ int64_t magnitude_sum = 0;
+ int valid_count = 0;
+
+ if (valid_mask[center] == 0)
+ continue;
+ for (size_t row = center_row - MILAN_QUALITY_PATCH_RADIUS;
+ row <= center_row + MILAN_QUALITY_PATCH_RADIUS; row++)
+ for (size_t column = center_column - MILAN_QUALITY_PATCH_RADIUS;
+ column <= center_column + MILAN_QUALITY_PATCH_RADIUS;
+ column++)
+ {
+ size_t index = row * columns + column;
+
+ if (valid_mask[index] != 0)
+ {
+ magnitude_sum += magnitude[index];
+ valid_count++;
+ }
+ }
+ if (valid_count <
+ (MILAN_QUALITY_PATCH_WIDTH * MILAN_QUALITY_PATCH_WIDTH) /
+ MILAN_QUALITY_PATCH_MINIMUM_VALID_DIVISOR)
+ continue;
+
+ int threshold = MILAN_QUALITY_PATCH_GRADIENT_FLOOR;
+ if (!fixed_threshold)
+ {
+ threshold =
+ (int) ((valid_count / 2 + magnitude_sum) / valid_count);
+ if (threshold < MILAN_QUALITY_PATCH_GRADIENT_FLOOR)
+ threshold = MILAN_QUALITY_PATCH_GRADIENT_FLOOR;
+ }
+
+ int selected_count = 0;
+ int64_t x_square_sum = 0;
+ int64_t y_square_sum = 0;
+ int64_t cross_sum = 0;
+ for (size_t row = center_row - MILAN_QUALITY_PATCH_RADIUS;
+ row <= center_row + MILAN_QUALITY_PATCH_RADIUS; row++)
+ for (size_t column = center_column - MILAN_QUALITY_PATCH_RADIUS;
+ column <= center_column + MILAN_QUALITY_PATCH_RADIUS;
+ column++)
+ {
+ size_t index = row * columns + column;
+
+ if (magnitude[index] >= threshold)
+ {
+ int x = gradient_x[index];
+ int y = gradient_y[index];
+
+ x_square_sum += x * x;
+ y_square_sum += y * y;
+ cross_sum += x * y;
+ selected_count++;
+ }
+ }
+ if (selected_count <
+ (MILAN_QUALITY_PATCH_WIDTH * MILAN_QUALITY_PATCH_WIDTH) /
+ MILAN_QUALITY_PATCH_MINIMUM_SELECTED_DIVISOR)
+ {
+ patch_scores[center] = 0;
+ score_histogram[0]++;
+ (*scored_patches)++;
+ continue;
+ }
+
+ int64_t rounding = selected_count / 2;
+ int64_t x_square = (rounding + x_square_sum) / selected_count;
+ int64_t y_square = (rounding + y_square_sum) / selected_count;
+ int64_t cross = (rounding + cross_sum) / selected_count;
+ int64_t average_square = (x_square + y_square) / 2;
+ int64_t anisotropy =
+ ((x_square * y_square - cross * cross) * MILAN_QUALITY_Q16_ONE) /
+ (average_square * average_square + 1);
+
+ if (anisotropy < 0)
+ anisotropy = 0;
+ int64_t score = MILAN_QUALITY_Q16_ONE - anisotropy;
+ if (score < 0)
+ score = 0;
+ int score_percent = (int) (
+ (score * MILAN_QUALITY_PERCENT_SCALE) >> MILAN_QUALITY_Q16_SHIFT);
+ if (score_percent > MILAN_QUALITY_PERCENT_SCALE)
+ score_percent = MILAN_QUALITY_PERCENT_SCALE;
+ patch_scores[center] = (int32_t) score;
+ score_histogram[score_percent]++;
+ *score_sum += score;
+ (*scored_patches)++;
+ }
+ }
+}
+
+static int
+quality_patch_score_core (const uint8_t *frame,
+ const uint8_t *valid_mask,
+ size_t rows,
+ size_t columns,
+ int fixed_threshold,
+ uint8_t *refined_mask,
+ int *patch_score)
+{
+ size_t count;
+ int32_t *gradient_x = NULL;
+ int32_t *gradient_y = NULL;
+ int32_t *magnitude = NULL;
+ int32_t *patch_scores = NULL;
+ int score_histogram[MILAN_QUALITY_SCORE_BIN_COUNT] = { 0 };
+ int64_t score_sum = 0;
+ int scored_patches = 0;
+
+ if (!frame || !valid_mask || !patch_score ||
+ rows < MILAN_QUALITY_PATCH_WIDTH || columns < MILAN_QUALITY_PATCH_WIDTH ||
+ columns > SIZE_MAX / rows)
+ return -1;
+
+ count = rows * columns;
+ if (count > SIZE_MAX / sizeof (*gradient_x))
+ return -1;
+ gradient_x = calloc (count, sizeof (*gradient_x));
+ gradient_y = calloc (count, sizeof (*gradient_y));
+ magnitude = calloc (count, sizeof (*magnitude));
+ patch_scores = malloc (count * sizeof (*patch_scores));
+ if (!gradient_x || !gradient_y || !magnitude || !patch_scores)
+ goto allocation_failed;
+ for (size_t i = 0; i < count; i++)
+ patch_scores[i] = -1;
+ if (refined_mask)
+ memcpy (refined_mask, valid_mask, count);
+
+ quality_prepare_patch_gradients (
+ frame, valid_mask, rows, columns, gradient_x, gradient_y, magnitude);
+
+ quality_accumulate_patch_scores (
+ valid_mask, gradient_x, gradient_y, magnitude, rows, columns,
+ fixed_threshold, patch_scores, score_histogram, &score_sum,
+ &scored_patches);
+
+ *patch_score = scored_patches != 0 ?
+ (int) (((((scored_patches / 2) + score_sum) /
+ scored_patches) * MILAN_QUALITY_PERCENT_SCALE) >>
+ MILAN_QUALITY_Q16_SHIFT) :
+ 0;
+ if (!fixed_threshold)
+ *patch_score += 5;
+ if (refined_mask)
+ quality_rewrite_patch_mask (
+ patch_scores, score_histogram, scored_patches, rows, columns, count,
+ refined_mask);
+ free (patch_scores);
+ free (magnitude);
+ free (gradient_y);
+ free (gradient_x);
+ return 0;
+
+allocation_failed:
+ free (patch_scores);
+ free (magnitude);
+ free (gradient_y);
+ free (gradient_x);
+ return -1;
+}
+
+static int
+quality_mask_fraction_core (const uint8_t *source,
+ const uint8_t *valid_mask,
+ size_t rows,
+ size_t columns,
+ int *mask_fraction)
+{
+ size_t count = rows * columns;
+ uint8_t *classes = malloc (count);
+ int histogram[MILAN_QUALITY_RING_HISTOGRAM_SIZE] = { 0 };
+
+ if (!classes)
+ return -1;
+ memset (classes, MILAN_QUALITY_RING_UNCLASSIFIED, count);
+ for (size_t row = 1; row + 1 < rows; row++)
+ for (size_t column = 1; column + 1 < columns; column++)
+ {
+ size_t index = row * columns + column;
+
+ if (valid_mask[index] == 0)
+ continue;
+ int center = source[index];
+ int ring[MILAN_QUALITY_RING_SIZE] = {
+ source[index - columns - 1] - center > MILAN_QUALITY_RING_CONTRAST_DELTA,
+ source[index - columns] - center > MILAN_QUALITY_RING_CONTRAST_DELTA,
+ source[index - columns + 1] - center > MILAN_QUALITY_RING_CONTRAST_DELTA,
+ source[index + 1] - center > MILAN_QUALITY_RING_CONTRAST_DELTA,
+ source[index + columns + 1] - center > MILAN_QUALITY_RING_CONTRAST_DELTA,
+ source[index + columns] - center > MILAN_QUALITY_RING_CONTRAST_DELTA,
+ source[index + columns - 1] - center > MILAN_QUALITY_RING_CONTRAST_DELTA,
+ source[index - 1] - center > MILAN_QUALITY_RING_CONTRAST_DELTA,
+ };
+ int transitions = 0;
+ int neighbors = 0;
+
+ for (size_t i = 0; i < MILAN_QUALITY_RING_SIZE; i++)
+ {
+ transitions += ring[i] != ring[(i + 1) & MILAN_QUALITY_RING_INDEX_MASK];
+ neighbors += ring[i];
+ }
+ if (transitions < MILAN_QUALITY_RING_TRANSITION_LIMIT)
+ classes[index] = (uint8_t) neighbors;
+ }
+ int classified = 0;
+ for (size_t i = 0; i < count; i++)
+ if (valid_mask[i] != 0)
+ {
+ histogram[classes[i]]++;
+ classified += classes[i] < MILAN_QUALITY_RING_UNCLASSIFIED;
+ }
+ *mask_fraction = classified != 0 ?
+ histogram[MILAN_QUALITY_RING_TARGET_CLASS] *
+ MILAN_QUALITY_PERCENT_SCALE / classified :
+ 0;
+ free (classes);
+ return 0;
+}
+
+int
+goodix_milan_preprocess_quality (const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ int *quality,
+ int *coverage)
+{
+ size_t count;
+ uint8_t *coverage_mask = NULL;
+ uint8_t *valid_mask = NULL;
+ uint8_t *refined_mask = NULL;
+ int raw_coverage;
+ int original_valid_score;
+ int propagated_valid_score;
+ int patch_score;
+ int mask_fraction;
+ int result = -1;
+
+ if (!frame || !quality || !coverage || rows == 0 || columns == 0 ||
+ columns > SIZE_MAX / rows)
+ return -1;
+
+ count = rows * columns;
+ coverage_mask = malloc (count);
+ valid_mask = malloc (count);
+ refined_mask = malloc (count);
+ if (!coverage_mask || !valid_mask || !refined_mask)
+ goto out;
+
+ if (goodix_milan_preprocess_quality_coverage_mask (
+ frame, rows, columns, coverage_mask, &raw_coverage) != 0)
+ goto out;
+ goodix_milan_preprocess_quality_valid_mask (
+ frame, rows, columns, valid_mask, &original_valid_score);
+ propagated_valid_score =
+ goodix_milan_preprocess_quality_mask_coverage (valid_mask, count);
+ if (quality_patch_score_core (
+ frame, valid_mask, rows, columns, 1, refined_mask, &patch_score) != 0 ||
+ quality_mask_fraction_core (
+ frame, refined_mask, rows, columns, &mask_fraction) != 0 ||
+ quality_combine_core (
+ raw_coverage, propagated_valid_score, patch_score, mask_fraction,
+ 35, 7, 1, quality, coverage) != 0)
+ goto out;
+
+ result = 0;
+
+out:
+ free (refined_mask);
+ free (valid_mask);
+ free (coverage_mask);
+ return result;
+}
+
+void
+goodix_milan_feature_pack_inline_mask (const uint8_t *validity_mask,
+ size_t rows,
+ size_t columns,
+ uint8_t *inline_mask)
+{
+ size_t block_rows = (rows + 3) / 4;
+ size_t block_columns = (columns + 3) / 4;
+
+ memset (inline_mask, 0, (block_rows * block_columns + 7) / 8);
+ for (size_t block_row = 0; block_row < block_rows; block_row++)
+ for (size_t block_column = 0; block_column < block_columns; block_column++)
+ {
+ size_t foreground = 0;
+ size_t pixels = 0;
+
+ for (size_t y = block_row * 4;
+ y < rows && y < block_row * 4 + 4; y++)
+ for (size_t x = block_column * 4;
+ x < columns && x < block_column * 4 + 4; x++)
+ {
+ foreground += validity_mask[y * columns + x] != 0;
+ pixels++;
+ }
+ if (foreground * 2 >= pixels)
+ {
+ size_t bit = block_row * block_columns + block_column;
+
+ inline_mask[bit / 8] |= (uint8_t) (1U << (bit & 7));
+ }
+ }
+}
+
+int
+goodix_milan_feature_base_maps_with_validity (
+ const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ uint8_t *high_bitmap,
+ uint8_t *low_bitmap,
+ uint8_t *feature_mask,
+ uint8_t *inline_mask,
+ uint8_t *validity_mask)
+{
+ size_t cropped_columns;
+ size_t cropped_count;
+ size_t map_columns;
+ size_t map_rows;
+ size_t map_count;
+ size_t bitmap_size;
+ uint8_t *cropped = NULL;
+ uint8_t *mask = NULL;
+ uint16_t *horizontal = NULL;
+ uint8_t *blurred = NULL;
+ int ignored_coverage;
+ int result = -1;
+
+ if (!frame || !high_bitmap || !low_bitmap || !feature_mask || rows < 2 ||
+ columns < 8 || columns > SIZE_MAX / rows)
+ return -1;
+
+ cropped_columns = (columns / 8) * 8;
+ cropped_count = cropped_columns * rows;
+ map_columns = cropped_columns / 2;
+ map_rows = rows / 2;
+ map_count = map_columns * map_rows;
+ bitmap_size = (map_count + 7) / 8;
+ cropped = malloc (cropped_count);
+ mask = malloc (cropped_count);
+ horizontal = malloc (cropped_count * sizeof(*horizontal));
+ blurred = malloc (cropped_count);
+ if (!cropped || !mask || !horizontal || !blurred)
+ goto out;
+
+ size_t crop_offset = (columns - cropped_columns) / 2;
+ for (size_t row = 0; row < rows; row++)
+ memcpy (cropped + row * cropped_columns,
+ frame + row * columns + crop_offset,
+ cropped_columns);
+
+ if (quality_coverage_mask_core (cropped, rows, cropped_columns, 0x6e, 1,
+ mask, &ignored_coverage) != 0)
+ goto out;
+ if (validity_mask)
+ memcpy (validity_mask, mask, cropped_count);
+
+ quality_gaussian_reflect101 (
+ cropped, rows, cropped_columns, milan_quality_gaussian6_kernel,
+ sizeof (milan_quality_gaussian6_kernel) /
+ sizeof (milan_quality_gaussian6_kernel[0]),
+ horizontal, blurred);
+
+ memset (high_bitmap, 0, bitmap_size);
+ memset (low_bitmap, 0, bitmap_size);
+ for (size_t row = 0; row < map_rows; row++)
+ {
+ for (size_t column = 0; column < map_columns; column++)
+ {
+ size_t source_index = row * 2 * cropped_columns + column * 2;
+ size_t map_index = row * map_columns + column;
+ uint8_t bit = (uint8_t) (1U << (map_index & 7));
+
+ feature_mask[map_index] = mask[source_index];
+ if (blurred[source_index] >= 0xc9)
+ high_bitmap[map_index >> 3] |= bit;
+ if (blurred[source_index] >= 0x38)
+ low_bitmap[map_index >> 3] |= bit;
+ }
+ }
+ if (inline_mask)
+ goodix_milan_feature_pack_inline_mask (
+ mask, rows, cropped_columns, inline_mask);
+ result = 0;
+
+out:
+ free (blurred);
+ free (horizontal);
+ free (mask);
+ free (cropped);
+ return result;
+}
+
+int
+goodix_milan_feature_base_maps (const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ uint8_t *high_bitmap,
+ uint8_t *low_bitmap,
+ uint8_t *feature_mask,
+ uint8_t *inline_mask)
+{
+ return goodix_milan_feature_base_maps_with_validity (
+ frame, rows, columns, high_bitmap, low_bitmap, feature_mask, inline_mask,
+ NULL);
+}
+
+
+static int
+milan_profile9_prepare_contrast_source (const uint16_t *source,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ uint16_t *output)
+{
+ const uint32_t gaussian_side = 6980;
+ const uint32_t gaussian_center = 51576;
+ size_t count = rows * columns;
+ uint32_t *sum_integral = NULL;
+ uint32_t *count_integral = NULL;
+ uint16_t *recentered = NULL;
+ uint16_t *smoothed = NULL;
+ uint16_t *horizontal = NULL;
+ int result = -1;
+
+ sum_integral = calloc (count, sizeof(*sum_integral));
+ count_integral = calloc (count, sizeof(*count_integral));
+ recentered = malloc (count * sizeof(*recentered));
+ smoothed = malloc (count * sizeof(*smoothed));
+ horizontal = malloc (count * sizeof(*horizontal));
+ if (!sum_integral || !count_integral || !recentered || !smoothed ||
+ !horizontal)
+ goto out;
+
+ for (size_t row = 0; row < rows; row++)
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t index = row * columns + column;
+ uint32_t value = mask[index] != 0 ? source[index] : 0;
+ uint32_t valid = mask[index] != 0;
+
+ if (column != 0)
+ {
+ value += sum_integral[index - 1];
+ valid += count_integral[index - 1];
+ }
+ if (row != 0)
+ {
+ value += sum_integral[index - columns];
+ valid += count_integral[index - columns];
+ }
+ if (row != 0 && column != 0)
+ {
+ value -= sum_integral[index - columns - 1];
+ valid -= count_integral[index - columns - 1];
+ }
+ sum_integral[index] = value;
+ count_integral[index] = valid;
+ }
+
+ for (size_t row = 0; row < rows; row++)
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t index = row * columns + column;
+ size_t first_row = row > 5 ? row - 5 : 0;
+ size_t last_row = row + 5 < rows ? row + 5 : rows - 1;
+ size_t first_column = column > 5 ? column - 5 : 0;
+ size_t last_column =
+ column + 5 < columns ? column + 5 : columns - 1;
+ uint32_t sum;
+ uint32_t valid;
+
+ if (mask[index] == 0)
+ {
+ recentered[index] = 3000;
+ continue;
+ }
+ sum = sum_integral[last_row * columns + last_column];
+ valid = count_integral[last_row * columns + last_column];
+ if (first_row != 0)
+ {
+ sum -= sum_integral[(first_row - 1) * columns + last_column];
+ valid -= count_integral[(first_row - 1) * columns + last_column];
+ }
+ if (first_column != 0)
+ {
+ sum -= sum_integral[last_row * columns + first_column - 1];
+ valid -= count_integral[last_row * columns + first_column - 1];
+ }
+ if (first_row != 0 && first_column != 0)
+ {
+ sum += sum_integral[(first_row - 1) * columns + first_column - 1];
+ valid +=
+ count_integral[(first_row - 1) * columns + first_column - 1];
+ }
+ uint32_t mean = valid != 0 ? (sum + valid / 2) / valid : 0;
+ int32_t value = (int32_t) source[index] - (int32_t) mean + 3000;
+
+ recentered[index] = (uint16_t) (value > 0 ? value : 0);
+ }
+
+ memcpy (smoothed, recentered, count * sizeof(*smoothed));
+ for (size_t row = 1; row + 1 < rows; row++)
+ for (size_t column = 1; column + 1 < columns; column++)
+ {
+ size_t index = row * columns + column;
+ uint32_t sum =
+ recentered[index - columns - 1] +
+ 2U * recentered[index - columns] +
+ recentered[index - columns + 1] +
+ 2U * recentered[index - 1] + 4U * recentered[index] +
+ 2U * recentered[index + 1] + recentered[index + columns - 1] +
+ 2U * recentered[index + columns] +
+ recentered[index + columns + 1];
+
+ smoothed[index] = (uint16_t) ((sum + 8) >> 4);
+ }
+
+ for (size_t row = 0; row < rows; row++)
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t left = goodix_milan_reflect101_index (
+ (ptrdiff_t) column - 1, columns);
+ size_t right = goodix_milan_reflect101_index (
+ (ptrdiff_t) column + 1, columns);
+ uint32_t sum = gaussian_side * smoothed[row * columns + left] +
+ gaussian_center * smoothed[row * columns + column] +
+ gaussian_side * smoothed[row * columns + right];
+
+ horizontal[row * columns + column] = (uint16_t) (sum >> 16);
+ }
+ for (size_t row = 0; row < rows; row++)
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t above = goodix_milan_reflect101_index (
+ (ptrdiff_t) row - 1, rows);
+ size_t below = goodix_milan_reflect101_index (
+ (ptrdiff_t) row + 1, rows);
+ uint32_t sum = gaussian_side * horizontal[above * columns + column] +
+ gaussian_center * horizontal[row * columns + column] +
+ gaussian_side * horizontal[below * columns + column];
+
+ output[row * columns + column] = (uint16_t) (sum >> 16);
+ }
+ result = 0;
+
+out:
+ free (horizontal);
+ free (smoothed);
+ free (recentered);
+ free (count_integral);
+ free (sum_integral);
+ return result;
+}
+
+static void
+milan_horizontal_extrema (const uint16_t *source,
+ size_t rows,
+ size_t columns,
+ uint16_t *minimums,
+ uint16_t *maximums)
+{
+ for (size_t row = 0; row < rows; row++)
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t first = column > 5 ? column - 5 : 0;
+ size_t last = column + 5 < columns ? column + 5 : columns - 1;
+ uint16_t minimum = UINT16_MAX;
+ uint16_t maximum = 0;
+
+ for (size_t x = first; x <= last; x++)
+ {
+ uint16_t value = source[row * columns + x];
+
+ if (value < minimum)
+ minimum = value;
+ if (value > maximum)
+ maximum = value;
+ }
+ minimums[row * columns + column] = minimum;
+ maximums[row * columns + column] = maximum;
+ }
+}
+
+static void
+milan_vertical_extrema (const uint16_t *source,
+ size_t rows,
+ size_t columns,
+ uint16_t *minimums,
+ uint16_t *maximums)
+{
+ for (size_t row = 0; row < rows; row++)
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t first = row > 5 ? row - 5 : 0;
+ size_t last = row + 5 < rows ? row + 5 : rows - 1;
+ uint16_t minimum = UINT16_MAX;
+ uint16_t maximum = 0;
+
+ for (size_t y = first; y <= last; y++)
+ {
+ uint16_t value = source[y * columns + column];
+
+ if (value < minimum)
+ minimum = value;
+ if (value > maximum)
+ maximum = value;
+ }
+ minimums[row * columns + column] = minimum;
+ maximums[row * columns + column] = maximum;
+ }
+}
+
+static void
+milan_merge_extrema (const uint16_t *vertical_min,
+ const uint16_t *vertical_max,
+ size_t count,
+ uint16_t *horizontal_min,
+ uint16_t *horizontal_max)
+{
+ for (size_t i = 0; i < count; i++)
+ {
+ if (vertical_max[i] > horizontal_max[i])
+ horizontal_max[i] = vertical_max[i];
+ if (vertical_min[i] < horizontal_min[i])
+ horizontal_min[i] = vertical_min[i];
+ }
+}
+
+static void
+milan_render_local_contrast (const uint16_t *source,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ const uint16_t *minimums,
+ const uint16_t *maximums,
+ int refine_diagonals,
+ uint8_t *output)
+{
+ for (size_t row = 0; row < rows; row++)
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t index = row * columns + column;
+ uint16_t lower = minimums[index];
+ uint16_t upper = maximums[index];
+
+ if (refine_diagonals)
+ {
+ for (int row_delta = -1; row_delta <= 1; row_delta += 2)
+ {
+ size_t neighbor_row;
+
+ if ((row_delta < 0 && row == 0) ||
+ (row_delta > 0 && row + 1 == rows))
+ continue;
+ neighbor_row = row_delta < 0 ? row - 1 : row + 1;
+ for (int column_delta = -1; column_delta <= 1;
+ column_delta += 2)
+ {
+ size_t neighbor_column;
+ size_t neighbor;
+
+ if ((column_delta < 0 && column == 0) ||
+ (column_delta > 0 && column + 1 == columns))
+ continue;
+ neighbor_column =
+ column_delta < 0 ? column - 1 : column + 1;
+ neighbor = neighbor_row * columns + neighbor_column;
+ if (minimums[neighbor] > lower)
+ lower = minimums[neighbor];
+ if (maximums[neighbor] < upper)
+ upper = maximums[neighbor];
+ }
+ }
+ }
+
+ if (mask[index] == 0)
+ {
+ output[index] = UINT8_MAX;
+ }
+ else if (upper == lower)
+ {
+ output[index] = 0;
+ }
+ else
+ {
+ int scaled = ((int) source[index] - (int) lower) * UINT8_MAX /
+ ((int) upper - (int) lower);
+
+ if (scaled < 0)
+ scaled = 0;
+ else if (scaled > UINT8_MAX)
+ scaled = UINT8_MAX;
+ output[index] = (uint8_t) (UINT8_MAX - scaled);
+ }
+ }
+}
+
+static int
+milan_contrast_core (const uint16_t *source,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ uint8_t *output,
+ int refine_diagonals)
+{
+ size_t count;
+ uint16_t *horizontal_min;
+ uint16_t *horizontal_max;
+ uint16_t *vertical_min;
+ uint16_t *vertical_max;
+
+ if (rows != 0 && columns > SIZE_MAX / rows)
+ return -1;
+
+ count = rows * columns;
+ if (count > SIZE_MAX / sizeof (uint16_t))
+ return -1;
+
+ horizontal_min = malloc (count * sizeof (*horizontal_min));
+ horizontal_max = malloc (count * sizeof (*horizontal_max));
+ vertical_min = malloc (count * sizeof (*vertical_min));
+ vertical_max = malloc (count * sizeof (*vertical_max));
+ if (!horizontal_min || !horizontal_max || !vertical_min || !vertical_max)
+ goto allocation_failed;
+
+ milan_horizontal_extrema (
+ source, rows, columns, horizontal_min, horizontal_max);
+ milan_vertical_extrema (
+ source, rows, columns, vertical_min, vertical_max);
+ milan_merge_extrema (
+ vertical_min, vertical_max, count, horizontal_min, horizontal_max);
+ milan_render_local_contrast (
+ source, mask, rows, columns, horizontal_min, horizontal_max,
+ refine_diagonals, output);
+
+ free (vertical_max);
+ free (vertical_min);
+ free (horizontal_max);
+ free (horizontal_min);
+ return 0;
+
+allocation_failed:
+ free (vertical_max);
+ free (vertical_min);
+ free (horizontal_max);
+ free (horizontal_min);
+ return -1;
+}
+
+int
+goodix_milan_preprocess_contrast (const uint16_t *source,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ uint8_t *output)
+{
+ size_t count;
+ uint16_t *profile_source;
+ int result;
+
+ if (!source || !mask || !output || rows == 0 || columns == 0 ||
+ columns > SIZE_MAX / rows)
+ return -1;
+ count = rows * columns;
+ if (count > SIZE_MAX / sizeof(*profile_source))
+ return -1;
+ profile_source = malloc (count * sizeof(*profile_source));
+ if (!profile_source)
+ return -1;
+ result = milan_profile9_prepare_contrast_source (
+ source, mask, rows, columns, profile_source);
+ if (result == 0)
+ result = milan_contrast_core (
+ profile_source, mask, rows, columns, output, 1);
+ free (profile_source);
+ return result;
+}
+
+static void
+milan_profile9_encode_metadata (uint8_t *image,
+ const uint8_t *mask,
+ size_t rows,
+ size_t columns,
+ int mode,
+ int apply_mask)
+{
+ if (!image || !mask || rows == 0 || columns < 8 || mode == 0)
+ return;
+ size_t prefix = columns - 8;
+ int prefix_ok = 1;
+
+ for (size_t column = 0; column < prefix; column++)
+ if ((image[column] & 1) != (column & 1))
+ {
+ prefix_ok = 0;
+ break;
+ }
+ if (!prefix_ok)
+ {
+ for (size_t column = prefix; column < columns; column++)
+ image[column] &= 0xfe;
+ for (size_t column = 0; column < prefix; column++)
+ image[column] = (uint8_t) ((image[column] & 0xfe) | (column & 1));
+ }
+
+ switch (mode)
+ {
+ case 1:
+ image[columns - 8] |= 1;
+ image[columns - 7] &= 0xfe;
+ break;
+ case 2:
+ image[columns - 8] |= 1;
+ image[columns - 7] |= 1;
+ break;
+ case 3:
+ image[columns - 8] &= 0xfe;
+ image[columns - 7] |= 1;
+ break;
+ case 4:
+ image[columns - 8] &= 0xfe;
+ image[columns - 7] &= 0xfe;
+ break;
+ case 5:
+ image[columns - 5] |= 1;
+ image[columns - 4] &= 0xfe;
+ image[columns - 3] &= 0xfe;
+ break;
+ case 6:
+ image[columns - 5] &= 0xfe;
+ image[columns - 4] |= 1;
+ image[columns - 3] &= 0xfe;
+ break;
+ case 7:
+ image[columns - 5] |= 1;
+ image[columns - 4] |= 1;
+ image[columns - 3] &= 0xfe;
+ break;
+ case 8:
+ image[columns - 5] &= 0xfe;
+ image[columns - 4] &= 0xfe;
+ image[columns - 3] |= 1;
+ break;
+ case 9:
+ image[columns - 5] |= 1;
+ image[columns - 4] &= 0xfe;
+ image[columns - 3] |= 1;
+ break;
+ default:
+ image[columns - 5] &= 0xfe;
+ image[columns - 4] &= 0xfe;
+ image[columns - 3] &= 0xfe;
+ break;
+ }
+ if (apply_mask)
+ {
+ int marker_was_set = (image[columns - 6] & 1) != 0;
+
+ image[columns - 6] |= 1;
+ for (size_t i = columns; i < rows * columns; i++)
+ {
+ if (!marker_was_set)
+ image[i] = (uint8_t) ((image[i] & 0xfe) | (mask[i] == 0));
+ else if (mask[i] != 0)
+ image[i] &= 0xfe;
+ }
+ }
+}
+
+/*
+ * Goodix 53x5 driver for libfprint - Milan post-render processing
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+static void
+milan_profile9_make_reciprocal_plane (const uint16_t *application_gain,
+ size_t count,
+ uint16_t *output)
+{
+ for (size_t i = 0; i < count; i++)
+ output[i] = application_gain[i] == 0
+ ? (uint16_t) (UINT32_C(8000) << 13)
+ : (uint16_t) ((UINT32_C(8000) * MILAN_FIXED_ONE +
+ application_gain[i] / 2) /
+ application_gain[i]);
+}
+
+static int
+milan_profile9_diagnostic_contrast (const uint16_t *source,
+ const uint8_t *render_mask,
+ size_t rows,
+ size_t columns,
+ uint8_t *output)
+{
+ size_t count = rows * columns;
+ uint16_t *prepared = NULL;
+ int *histogram = NULL;
+ size_t selected = 0;
+ int lower_bin = 0;
+ int upper_bin = 4999;
+ int result = -1;
+
+ prepared = malloc (count * sizeof(*prepared));
+ histogram = calloc (5000, sizeof(*histogram));
+ if (!prepared || !histogram)
+ goto out;
+ if (milan_profile9_prepare_contrast_source (
+ source, render_mask, rows, columns, prepared) != 0)
+ goto out;
+
+ for (size_t i = 0; i < count; i++)
+ if (render_mask[i] != 0)
+ {
+ uint32_t bin = prepared[i] >> 2;
+
+ if (bin > 4999)
+ bin = 4999;
+ histogram[bin]++;
+ selected++;
+ }
+
+ size_t cumulative = 0;
+ for (upper_bin = 4999; upper_bin >= 0; upper_bin--)
+ {
+ cumulative += histogram[upper_bin];
+ if (selected * 15 <= cumulative * 100)
+ break;
+ }
+ if (upper_bin < 0)
+ upper_bin = 0;
+
+ cumulative = 0;
+ for (lower_bin = 0; lower_bin < 5000; lower_bin++)
+ {
+ cumulative += histogram[lower_bin];
+ if (selected * 5 <= cumulative * 100)
+ break;
+ }
+ if (lower_bin == 5000)
+ lower_bin = INT_MAX / 4;
+
+ int lower = lower_bin * 4;
+ int upper = upper_bin * 4;
+
+ if (upper - lower < 200)
+ upper = lower + 200;
+ for (size_t i = 0; i < count; i++)
+ {
+ int value = 0;
+
+ if (render_mask[i] != 0 && upper > lower)
+ {
+ value = ((int) prepared[i] - lower) * UINT8_MAX /
+ (upper - lower);
+ if (value < 0)
+ value = 0;
+ else if (value > UINT8_MAX)
+ value = UINT8_MAX;
+ }
+ output[i] = (uint8_t) (UINT8_MAX - value);
+ }
+ result = 0;
+
+out:
+ free (histogram);
+ free (prepared);
+ return result;
+}
+
+static int
+milan_profile9_component_score (const uint8_t *frame,
+ const uint8_t *residual_mask,
+ size_t rows,
+ size_t columns,
+ int *score)
+{
+ int patch_score;
+ int mask_fraction;
+
+ if (quality_patch_score_core (
+ frame, residual_mask, rows, columns, 1, NULL, &patch_score) != 0 ||
+ quality_mask_fraction_core (
+ frame, residual_mask, rows, columns, &mask_fraction) != 0)
+ return -1;
+
+ *score = patch_score;
+ if (*score < 70)
+ {
+ if (mask_fraction < 25)
+ {
+ int factor = mask_fraction * 256 / 25;
+
+ *score = *score * factor >> 8;
+ *score = *score * factor >> 8;
+ }
+ if (mask_fraction >= 30)
+ *score += 15;
+ }
+ if (*score < 0)
+ *score = 0;
+ else if (*score > 100)
+ *score = 100;
+ return 0;
+}
+
+static int
+milan_profile9_center_rows (const uint16_t *source,
+ const uint8_t *render_mask,
+ size_t rows,
+ size_t columns,
+ uint16_t *centered)
+{
+ size_t count = rows * columns;
+ size_t mask_count = 0;
+
+ if (!source || !render_mask || !centered)
+ return -1;
+ for (size_t i = 0; i < count; i++)
+ mask_count += render_mask[i] != 0;
+ int mask_percent = (int) (mask_count * 100 / count);
+
+ for (size_t row = 0; row < rows; row++)
+ {
+ uint32_t sum = 0;
+ size_t contributors = 0;
+
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t index = row * columns + column;
+
+ if (mask_percent >= 96 || render_mask[index] != 0)
+ {
+ sum += source[index];
+ contributors++;
+ }
+ }
+ uint16_t mean = contributors != 0 ? (uint16_t) (sum / contributors) : 0;
+
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t index = row * columns + column;
+ int value;
+
+ if (mask_percent < 96 && render_mask[index] == 0)
+ value = 5000;
+ else
+ value = (int16_t) ((int) source[index] - mean + 5000);
+ centered[index] = (uint16_t) (value > 0 ? value : 0);
+ }
+ }
+ return 0;
+}
+
+static int
+milan_profile9_disagreement (const uint16_t *working,
+ const uint8_t *render_mask,
+ size_t rows,
+ size_t columns,
+ int selected_refined,
+ uint8_t *component_mask,
+ int *component_score,
+ int *component_flag,
+ int *disagreement)
+{
+ size_t count = rows * columns;
+ uint16_t *centered = NULL;
+ const uint16_t *diagnostic_source = working;
+ uint8_t *diagnostic = NULL;
+ uint8_t *gradient_mask = NULL;
+ size_t source_count = 0;
+ size_t missing_count = 0;
+ int ignored_coverage;
+ int result = -1;
+
+ diagnostic = malloc (count);
+ gradient_mask = malloc (count);
+ centered = selected_refined ? malloc (count * sizeof(*centered)) : NULL;
+ if (!diagnostic || !gradient_mask || (selected_refined && !centered))
+ goto out;
+ if (selected_refined)
+ {
+ if (milan_profile9_center_rows (
+ working, render_mask, rows, columns, centered) != 0)
+ goto out;
+ diagnostic_source = centered;
+ }
+ if (milan_profile9_diagnostic_contrast (
+ diagnostic_source, render_mask, rows, columns, diagnostic) != 0 ||
+ quality_coverage_mask_core (
+ diagnostic, rows, columns, 80, UINT8_MAX, gradient_mask,
+ &ignored_coverage) != 0)
+ goto out;
+
+ for (size_t i = 0; i < count; i++)
+ {
+ component_mask[i] = render_mask[i];
+ if (render_mask[i] != 0)
+ {
+ source_count++;
+ if (gradient_mask[i] == 0)
+ missing_count++;
+ else
+ component_mask[i] = 0;
+ }
+ }
+
+ *component_score = 0;
+ *component_flag = 0;
+ if (missing_count * 100 > source_count * 30)
+ {
+ if (milan_profile9_component_score (
+ diagnostic, component_mask, rows, columns,
+ component_score) != 0)
+ goto out;
+ if (*component_score < 15)
+ *component_flag = 1;
+ }
+ *disagreement =
+ (int) (((*component_flag ? missing_count : source_count) * 100) / count);
+ result = 0;
+
+out:
+ free (centered);
+ free (gradient_mask);
+ free (diagnostic);
+ return result;
+}
+
+static int
+milan_profile9_rerender (const uint16_t *source,
+ const uint8_t *render_mask,
+ size_t rows,
+ size_t columns,
+ int refined,
+ uint8_t *output)
+{
+ size_t count = rows * columns;
+ uint16_t *centered = NULL;
+ size_t mask_count = 0;
+ int result;
+
+ if (!refined)
+ return milan_contrast_core (
+ source, render_mask, rows, columns, output, 0);
+
+ centered = malloc (count * sizeof(*centered));
+ if (!centered)
+ return -1;
+ for (size_t i = 0; i < count; i++)
+ mask_count += render_mask[i] != 0;
+ int mask_percent = (int) (mask_count * 100 / count);
+
+ for (size_t row = 0; row < rows; row++)
+ {
+ uint32_t sum = 0;
+ size_t contributors = 0;
+
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t index = row * columns + column;
+
+ if (mask_percent >= 96 || render_mask[index] != 0)
+ {
+ sum += source[index];
+ contributors++;
+ }
+ }
+ uint16_t mean = contributors != 0 ? (uint16_t) (sum / contributors) : 0;
+
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t index = row * columns + column;
+ int value;
+
+ if (mask_percent < 96 && render_mask[index] == 0)
+ value = 5000;
+ else
+ value = (int16_t) ((int) source[index] - mean + 5000);
+ centered[index] = (uint16_t) (value > 0 ? value : 0);
+ }
+ }
+ result = milan_contrast_core (
+ centered, render_mask, rows, columns, output, 0);
+ free (centered);
+ return result;
+}
+
+static int
+milan_profile9_mean_absolute_difference (const uint8_t *first,
+ const uint8_t *second,
+ const uint8_t *mask,
+ size_t count)
+{
+ uint64_t sum = 0;
+ size_t samples = 0;
+
+ for (size_t i = 0; i < count; i++)
+ if (mask[i] != 0)
+ {
+ int difference = (int) first[i] - (int) second[i];
+
+ sum += difference < 0 ? -difference : difference;
+ samples++;
+ }
+ return samples != 0 ? (int) ((sum + samples / 2) / samples) : 0;
+}
+
+static int
+milan_profile9_post_render (GoodixMilanPreprocessState *state,
+ const uint16_t *normalized_live,
+ const uint16_t *setup_map,
+ const uint8_t *render_mask,
+ const uint16_t *working,
+ const uint16_t *optional_plane0,
+ const uint16_t *reciprocal_plane,
+ const uint8_t *selected,
+ const uint8_t *selection_mask,
+ int selected_refined,
+ GoodixMilanPreprocessPurpose purpose,
+ uint32_t *calibration_ready,
+ const uint8_t **first_metadata_mask,
+ uint8_t **first_metadata_owned_mask,
+ int *first_metadata_mode,
+ int *first_metadata_apply)
+{
+ const size_t rows = GOODIX_MILAN_SENSOR_ROWS;
+ const size_t columns = GOODIX_MILAN_SENSOR_COLUMNS;
+ const size_t count = GOODIX_MILAN_SENSOR_PIXELS;
+ uint16_t *nested_gain = NULL;
+ uint16_t *nested_output = NULL;
+ uint8_t *primary_render = NULL;
+ uint8_t *fallback_render = NULL;
+ uint8_t *component_mask = NULL;
+ const uint8_t *quality_mask;
+ size_t mask_count = 0;
+ uint32_t saved_sample_count;
+ uint32_t auxiliary_samples;
+ int component_score;
+ int component_flag;
+ int disagreement;
+ int primary_metric;
+ int fallback_metric = 200;
+ int quality_gate;
+ int mode = 0;
+ int status = 0;
+ int result = -1;
+
+ (void) purpose;
+ primary_render = malloc (count);
+ fallback_render = malloc (count);
+ component_mask = malloc (count);
+ if (!primary_render || !fallback_render || !component_mask)
+ goto out;
+
+ if (milan_profile9_disagreement (
+ working, render_mask, rows, columns, selected_refined, component_mask,
+ &component_score, &component_flag, &disagreement) != 0 ||
+ milan_profile9_rerender (
+ optional_plane0, render_mask, rows, columns, selected_refined,
+ primary_render) != 0)
+ goto out;
+
+ quality_mask = component_flag ? component_mask : selection_mask;
+ primary_metric = milan_profile9_mean_absolute_difference (
+ selected, primary_render, quality_mask, count);
+ quality_gate = primary_metric > 75;
+ if (!quality_gate && primary_metric > 55)
+ {
+ if (milan_contrast_core (
+ reciprocal_plane, render_mask, rows, columns,
+ fallback_render, 0) != 0)
+ goto out;
+ fallback_metric = milan_profile9_mean_absolute_difference (
+ selected, fallback_render, quality_mask, count);
+ quality_gate = fallback_metric < 80;
+ }
+
+ state->post_render.primary_metric = primary_metric;
+ state->post_render.fallback_metric = fallback_metric;
+ state->post_render.disagreement = disagreement;
+ state->post_render.component_score = component_score;
+ state->post_render.component_flag = component_flag;
+ state->post_render.quality_gate = quality_gate;
+
+ if (!quality_gate)
+ {
+ result = 0;
+ goto publish;
+ }
+
+ mode = 4;
+
+ for (size_t i = 0; i < count; i++)
+ mask_count += render_mask[i] != 0;
+ int mask_percent = (int) (mask_count * 100 / count);
+ int normalized_disagreement = mask_percent != 0
+ ? disagreement * 100 / mask_percent
+ : disagreement;
+
+ saved_sample_count = state->sample_count;
+ if (disagreement > 40 || normalized_disagreement > 33)
+ {
+ status = GOODIX_MILAN_PREPROCESS_RETRY;
+ mode = saved_sample_count < 100 && primary_metric > 85 ? 3 : 2;
+ }
+ if (saved_sample_count < 100 && disagreement > 90)
+ {
+ auxiliary_samples = state->auxiliary_sample_count;
+ nested_gain = malloc (count * sizeof(*nested_gain));
+ nested_output = malloc (count * sizeof(*nested_output));
+ if (!nested_gain || !nested_output)
+ goto out;
+ state->sample_count = 5;
+ goodix_milan_profile9_update_gain_ready (
+ auxiliary_samples, state->sample_count, calibration_ready);
+ if (first_update_frame_core (
+ normalized_live, setup_map, state->calibration_map,
+ state->application_gain_map, state->auxiliary_gain_map,
+ auxiliary_samples, state, *calibration_ready, rows, columns,
+ nested_gain, nested_output, NULL) != 0)
+ {
+ state->sample_count = saved_sample_count;
+ goto out;
+ }
+ state->sample_count = saved_sample_count;
+ state->post_render.update_applied = 1;
+ }
+ state->post_render.status = status;
+ result = status;
+
+publish:
+ *first_metadata_apply = component_flag;
+ *first_metadata_mode = mode;
+ if (component_flag)
+ {
+ *first_metadata_mask = component_mask;
+ *first_metadata_owned_mask = component_mask;
+ component_mask = NULL;
+ }
+ else
+ {
+ *first_metadata_mask = selection_mask;
+ *first_metadata_owned_mask = NULL;
+ }
+
+out:
+ free (component_mask);
+ free (fallback_render);
+ free (primary_render);
+ free (nested_output);
+ free (nested_gain);
+ return result;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/debug-hooks.c b/libfprint/drivers/goodix53x5/milan/debug-hooks.c
new file mode 100644
index 0000000..e6fa1cb
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/debug-hooks.c
@@ -0,0 +1,222 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan algorithm debug hooks
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/debug-hooks.h"
+
+#include "milan/antifake/antifake.h"
+
+#include <string.h>
+
+#if defined(GOODIX53X5_DEBUG) || defined(GOODIX53X5_PARITY)
+static void
+goodix_milan_debug_hash_bytes (GBytes *bytes,
+ gchar digest[65])
+{
+ gconstpointer data;
+ gsize size;
+ g_autofree gchar *checksum = NULL;
+
+ digest[0] = '\0';
+ if (!bytes)
+ return;
+ data = g_bytes_get_data (bytes, &size);
+ checksum = g_compute_checksum_for_data (G_CHECKSUM_SHA256, data, size);
+ g_strlcpy (digest, checksum ? checksum : "", 65);
+}
+
+void
+goodix_milan_debug_runtime_hash_after_match (
+ GoodixMilanRuntimeGalleryResult *result,
+ GBytes *after_match)
+{
+ goodix_milan_debug_hash_bytes (after_match, result->after_match_sha256);
+}
+#endif
+
+#ifdef GOODIX53X5_DEBUG
+static void
+goodix_milan_debug_hash_projection (
+ const GoodixMilanAntifakeBlob *projection,
+ gchar digest[GOODIX_MILAN_EXTRACTION_SHA256_SIZE])
+{
+ g_autofree gchar *checksum = g_compute_checksum_for_data (
+ G_CHECKSUM_SHA256, goodix_milan_antifake_const_data (projection),
+ GOODIX_MILAN_ANTIFAKE_DEFINED_MATERIAL_SIZE);
+
+ g_strlcpy (digest, checksum ? checksum : "",
+ GOODIX_MILAN_EXTRACTION_SHA256_SIZE);
+}
+
+void
+goodix_milan_debug_extraction_antifake (
+ GoodixMilanExtractionDiagnostics *diagnostics,
+ const guint16 *calibration,
+ const guint16 *raw_frame,
+ const guint8 *primary_contrast_plane,
+ const guint8 *feature_mask,
+ guint16 t_code,
+ guint16 dac_high,
+ guint16 dac_low,
+ guint16 sensor_subtype,
+ gint32 calibration_scalar)
+{
+ g_autofree GoodixMilanAntifakeBlob *diagnostic_antifake = NULL;
+
+ if (diagnostics && calibration && raw_frame &&
+ (diagnostic_antifake = g_try_malloc0 (
+ sizeof (*diagnostic_antifake))) != NULL)
+ {
+ GoodixMilanAntifakeBoundaryResult boundary = { 0 };
+ int status = goodix_milan_antifake_build_with_boundary (
+ calibration, raw_frame, primary_contrast_plane, feature_mask, 52 * 44,
+ GOODIX_MILAN_SENSOR_ROWS, GOODIX_MILAN_SENSOR_COLUMNS, t_code,
+ dac_high, dac_low, sensor_subtype, calibration_scalar,
+ diagnostic_antifake, sizeof (*diagnostic_antifake), &boundary);
+
+ if (status == 0 || status == GOODIX_MILAN_ANTIFAKE_AMBIGUOUS)
+ {
+ diagnostics->boundary_classification = boundary.classification;
+ diagnostics->zero_candidate_count = boundary.zero_candidate_count;
+ diagnostics->nonzero_candidate_count = boundary.nonzero_candidate_count;
+ goodix_milan_debug_hash_projection (
+ &boundary.zero_projection, diagnostics->zero_projection_sha256);
+ goodix_milan_debug_hash_projection (
+ &boundary.nonzero_projection,
+ diagnostics->nonzero_projection_sha256);
+ }
+ }
+}
+
+void
+goodix_milan_debug_runtime_gallery_result_free (
+ GoodixMilanRuntimeGalleryResult *result)
+{
+ g_clear_pointer (&result->input_template, g_bytes_unref);
+ g_clear_pointer (&result->after_match_template, g_bytes_unref);
+}
+
+void
+goodix_milan_debug_runtime_setup_failed (GoodixMilanRuntimeOutput *output,
+ gint32 status)
+{
+ output->preprocess_attempted = TRUE;
+ output->preprocess_status = status;
+ output->preprocess_status_available = TRUE;
+}
+
+void
+goodix_milan_debug_runtime_preprocess_started (GoodixMilanRuntimeOutput *output)
+{
+ output->preprocess_attempted = TRUE;
+}
+
+void
+goodix_milan_debug_runtime_preprocess_status (GoodixMilanRuntimeOutput *output,
+ gint32 status)
+{
+ output->preprocess_status = status;
+ output->preprocess_status_available = TRUE;
+}
+
+void
+goodix_milan_debug_runtime_preprocess_finished (GoodixMilanRuntimeOutput *output,
+ gint32 status,
+ const guint8 *processed)
+{
+ output->preprocess_completed = status == 0;
+ if (output->preprocess_completed ||
+ status == GOODIX_MILAN_PREPROCESS_RETRY_CLASSIFICATION)
+ output->processed_image = g_bytes_new (processed,
+ GOODIX_MILAN_SENSOR_PIXELS);
+}
+
+void
+goodix_milan_debug_runtime_extraction_started (GoodixMilanRuntimeOutput *output)
+{
+ output->extraction_attempted = TRUE;
+}
+
+void
+goodix_milan_debug_runtime_extraction_finished (GoodixMilanRuntimeOutput *output)
+{
+ output->extraction_completed = TRUE;
+}
+
+void
+goodix_milan_debug_runtime_gallery_input (GoodixMilanRuntimeGalleryResult *result,
+ GBytes *input_template)
+{
+ result->input_template = g_bytes_ref (input_template);
+ goodix_milan_debug_hash_bytes (input_template, result->input_template_sha256);
+}
+
+void
+goodix_milan_debug_runtime_gallery_validated (GoodixMilanRuntimeGalleryResult *result)
+{
+ result->validation_observed = TRUE;
+}
+
+void
+goodix_milan_debug_runtime_queue_before_match (GoodixMilanRuntimeGalleryResult *result,
+ const GoodixStudyQueue *queue)
+{
+ result->queue_before_match_observed = TRUE;
+ result->queue_state_before_match = queue->enabled_state;
+ result->queue_counter_before_match = queue->transaction_counter;
+ result->queue_occupied_before_match = goodix_milan_study_queue_occupied (queue);
+}
+
+void
+goodix_milan_debug_runtime_queue_after_match (GoodixMilanRuntimeGalleryResult *result,
+ const GoodixStudyQueue *queue)
+{
+ result->queue_after_match_observed = TRUE;
+ result->queue_occupied_after_match = goodix_milan_study_queue_occupied (queue);
+}
+
+void
+goodix_milan_debug_runtime_after_match (GoodixMilanRuntimeGalleryResult *result,
+ GBytes *after_match)
+{
+ result->after_match_template = g_bytes_ref (after_match);
+}
+
+void
+goodix_milan_debug_runtime_study_started (GoodixMilanRuntimeOutput *output)
+{
+ output->study_attempted = TRUE;
+}
+
+void
+goodix_milan_debug_runtime_queue_after_study (GoodixMilanRuntimeOutput *output,
+ gsize winner_position,
+ const GoodixStudyQueue *queue)
+{
+ GoodixMilanRuntimeGalleryResult *result =
+ g_ptr_array_index (output->gallery_results, winner_position);
+
+ result->queue_after_study_observed = TRUE;
+ result->queue_state_after_study = queue->enabled_state;
+ result->queue_counter_after_study = queue->transaction_counter;
+ result->queue_occupied_after_study = goodix_milan_study_queue_occupied (queue);
+}
+
+void
+goodix_milan_debug_runtime_study_finished (GoodixMilanRuntimeOutput *output)
+{
+ output->study_completed = TRUE;
+}
+
+void
+goodix_milan_debug_runtime_output_free (GoodixMilanRuntimeOutput *output)
+{
+ g_clear_pointer (&output->processed_image, g_bytes_unref);
+}
+#endif
diff --git a/libfprint/drivers/goodix53x5/milan/debug-hooks.h b/libfprint/drivers/goodix53x5/milan/debug-hooks.h
new file mode 100644
index 0000000..9cdb540
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/debug-hooks.h
@@ -0,0 +1,208 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan algorithm debug hooks
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include "milan/runtime.h"
+#include "milan/study/queue.h"
+
+#ifdef GOODIX53X5_DEBUG
+void goodix_milan_debug_runtime_gallery_result_free (GoodixMilanRuntimeGalleryResult *result);
+void goodix_milan_debug_runtime_setup_failed (GoodixMilanRuntimeOutput *output,
+ gint32 status);
+void goodix_milan_debug_runtime_preprocess_started (GoodixMilanRuntimeOutput *output);
+void goodix_milan_debug_runtime_preprocess_status (GoodixMilanRuntimeOutput *output,
+ gint32 status);
+void goodix_milan_debug_runtime_preprocess_finished (GoodixMilanRuntimeOutput *output,
+ gint32 status,
+ const guint8 *processed);
+void goodix_milan_debug_runtime_extraction_started (GoodixMilanRuntimeOutput *output);
+void goodix_milan_debug_runtime_extraction_finished (GoodixMilanRuntimeOutput *output);
+void goodix_milan_debug_runtime_gallery_input (GoodixMilanRuntimeGalleryResult *result,
+ GBytes *input_template);
+void goodix_milan_debug_runtime_gallery_validated (GoodixMilanRuntimeGalleryResult *result);
+void goodix_milan_debug_runtime_queue_before_match (GoodixMilanRuntimeGalleryResult *result,
+ const GoodixStudyQueue *queue);
+void goodix_milan_debug_runtime_queue_after_match (GoodixMilanRuntimeGalleryResult *result,
+ const GoodixStudyQueue *queue);
+void goodix_milan_debug_runtime_after_match (GoodixMilanRuntimeGalleryResult *result,
+ GBytes *after_match);
+void goodix_milan_debug_runtime_study_started (GoodixMilanRuntimeOutput *output);
+void goodix_milan_debug_runtime_queue_after_study (GoodixMilanRuntimeOutput *output,
+ gsize winner_position,
+ const GoodixStudyQueue *queue);
+void goodix_milan_debug_runtime_study_finished (GoodixMilanRuntimeOutput *output);
+void goodix_milan_debug_runtime_output_free (GoodixMilanRuntimeOutput *output);
+void goodix_milan_debug_extraction_antifake (GoodixMilanExtractionDiagnostics *diagnostics,
+ const guint16 *calibration,
+ const guint16 *raw_frame,
+ const guint8 *primary_contrast_plane,
+ const guint8 *feature_mask,
+ guint16 t_code,
+ guint16 dac_high,
+ guint16 dac_low,
+ guint16 sensor_subtype,
+ gint32 calibration_scalar);
+#else
+static inline void
+goodix_milan_debug_runtime_gallery_result_free (
+ GoodixMilanRuntimeGalleryResult *result)
+{
+ (void) result;
+}
+
+static inline void
+goodix_milan_debug_runtime_setup_failed (GoodixMilanRuntimeOutput *output,
+ gint32 status)
+{
+ (void) output;
+ (void) status;
+}
+
+static inline void
+goodix_milan_debug_runtime_preprocess_started (GoodixMilanRuntimeOutput *output)
+{
+ (void) output;
+}
+
+static inline void
+goodix_milan_debug_runtime_preprocess_status (GoodixMilanRuntimeOutput *output,
+ gint32 status)
+{
+ (void) output;
+ (void) status;
+}
+
+static inline void
+goodix_milan_debug_runtime_preprocess_finished (GoodixMilanRuntimeOutput *output,
+ gint32 status,
+ const guint8 *processed)
+{
+ (void) output;
+ (void) status;
+ (void) processed;
+}
+
+static inline void
+goodix_milan_debug_runtime_extraction_started (GoodixMilanRuntimeOutput *output)
+{
+ (void) output;
+}
+
+static inline void
+goodix_milan_debug_runtime_extraction_finished (GoodixMilanRuntimeOutput *output)
+{
+ (void) output;
+}
+
+static inline void
+goodix_milan_debug_runtime_gallery_input (GoodixMilanRuntimeGalleryResult *result,
+ GBytes *input_template)
+{
+ (void) result;
+ (void) input_template;
+}
+
+static inline void
+goodix_milan_debug_runtime_gallery_validated (GoodixMilanRuntimeGalleryResult *result)
+{
+ (void) result;
+}
+
+static inline void
+goodix_milan_debug_runtime_queue_before_match (GoodixMilanRuntimeGalleryResult *result,
+ const GoodixStudyQueue *queue)
+{
+ (void) result;
+ (void) queue;
+}
+
+static inline void
+goodix_milan_debug_runtime_queue_after_match (GoodixMilanRuntimeGalleryResult *result,
+ const GoodixStudyQueue *queue)
+{
+ (void) result;
+ (void) queue;
+}
+
+static inline void
+goodix_milan_debug_runtime_after_match (GoodixMilanRuntimeGalleryResult *result,
+ GBytes *after_match)
+{
+ (void) result;
+ (void) after_match;
+}
+
+static inline void
+goodix_milan_debug_runtime_study_started (GoodixMilanRuntimeOutput *output)
+{
+ (void) output;
+}
+
+static inline void
+goodix_milan_debug_runtime_queue_after_study (GoodixMilanRuntimeOutput *output,
+ gsize winner_position,
+ const GoodixStudyQueue *queue)
+{
+ (void) output;
+ (void) winner_position;
+ (void) queue;
+}
+
+static inline void
+goodix_milan_debug_runtime_study_finished (GoodixMilanRuntimeOutput *output)
+{
+ (void) output;
+}
+
+static inline void
+goodix_milan_debug_runtime_output_free (GoodixMilanRuntimeOutput *output)
+{
+ (void) output;
+}
+
+static inline void
+goodix_milan_debug_extraction_antifake (
+ GoodixMilanExtractionDiagnostics *diagnostics,
+ const guint16 *calibration,
+ const guint16 *raw_frame,
+ const guint8 *primary_contrast_plane,
+ const guint8 *feature_mask,
+ guint16 t_code,
+ guint16 dac_high,
+ guint16 dac_low,
+ guint16 sensor_subtype,
+ gint32 calibration_scalar)
+{
+ (void) diagnostics;
+ (void) calibration;
+ (void) raw_frame;
+ (void) primary_contrast_plane;
+ (void) feature_mask;
+ (void) t_code;
+ (void) dac_high;
+ (void) dac_low;
+ (void) sensor_subtype;
+ (void) calibration_scalar;
+}
+#endif
+
+#if defined(GOODIX53X5_DEBUG) || defined(GOODIX53X5_PARITY)
+void goodix_milan_debug_runtime_hash_after_match (GoodixMilanRuntimeGalleryResult *result,
+ GBytes *after_match);
+#else
+static inline void
+goodix_milan_debug_runtime_hash_after_match (GoodixMilanRuntimeGalleryResult *result,
+ GBytes *after_match)
+{
+ (void) result;
+ (void) after_match;
+}
+#endif
diff --git a/libfprint/drivers/goodix53x5/milan/enrollment/propagation.c b/libfprint/drivers/goodix53x5/milan/enrollment/propagation.c
new file mode 100644
index 0000000..aad5fed
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/enrollment/propagation.c
@@ -0,0 +1,115 @@
+/*
+ * Goodix 53x5 driver for libfprint - enrollment relation propagation
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/enrollment/propagation.h"
+
+int
+goodix_milan_enrollment_propagate_lower (
+ GoodixMilanRelationMatrix *matrix,
+ int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ size_t pivot,
+ const int32_t pivot_to_reference[6],
+ int32_t threshold,
+ GoodixMilanEnrollmentOverlapFunc overlap_func,
+ void *user_data)
+{
+ size_t worklist[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY];
+ size_t worklist_count = 1;
+
+ if (!matrix || !active || !pivot_to_reference || !overlap_func ||
+ pivot >= matrix->feature_count)
+ return -1;
+ worklist[0] = pivot;
+ for (size_t candidate = pivot; candidate-- > 0;)
+ {
+ if (active[candidate])
+ continue;
+ for (size_t position = worklist_count; position-- > 0;)
+ {
+ size_t node = worklist[position];
+ size_t child = position;
+ GoodixMilanRelationSlot *slot =
+ goodix_milan_enrollment_relation_slot (matrix, candidate, node);
+ int32_t overlap;
+ int32_t path[6];
+ int32_t candidate_to_pivot[6];
+ int32_t candidate_to_reference[6];
+
+ if (!slot || slot->values[0] < 0 ||
+ overlap_func (user_data, candidate, node, &overlap) != 0 ||
+ overlap <= threshold)
+ continue;
+ memcpy (path, slot->values + 1, sizeof(path));
+ /* An absent edge leaves the accumulated path at the same child. */
+ for (size_t route = position; route-- > 0;)
+ {
+ GoodixMilanRelationSlot *route_slot =
+ goodix_milan_enrollment_relation_slot (
+ matrix, worklist[route], worklist[child]);
+
+ if (route_slot && route_slot->values[0] >= 0)
+ {
+ goodix_milan_transform_compose (
+ route_slot->values + 1, path, path);
+ child = route;
+ }
+ }
+ if (goodix_milan_transform_invert (
+ path, candidate_to_pivot) != 0)
+ return -1;
+ goodix_milan_transform_compose (
+ pivot_to_reference, candidate_to_pivot, candidate_to_reference);
+ if (goodix_milan_relation_matrix_store_reference (
+ matrix, candidate, candidate_to_reference) != 0)
+ return -1;
+ active[candidate] = 1;
+ worklist[worklist_count++] = candidate;
+ break;
+ }
+ }
+ return 0;
+}
+
+int
+goodix_milan_enrollment_propagate_higher (
+ GoodixMilanRelationMatrix *matrix,
+ int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ size_t pivot,
+ size_t current,
+ const int32_t pivot_to_reference[6],
+ int32_t threshold,
+ GoodixMilanEnrollmentOverlapFunc overlap_func,
+ void *user_data)
+{
+ if (!matrix || !active || !pivot_to_reference || !overlap_func ||
+ pivot >= current || current > matrix->feature_count)
+ return -1;
+ for (size_t candidate = pivot + 1; candidate < current; candidate++)
+ {
+ GoodixMilanRelationSlot *slot;
+ int32_t overlap;
+ int32_t candidate_to_reference[6];
+
+ if (active[candidate])
+ continue;
+ slot = goodix_milan_enrollment_relation_slot (matrix, candidate, pivot);
+ if (!slot || slot->values[0] < 0 ||
+ overlap_func (user_data, candidate, pivot, &overlap) != 0 ||
+ overlap <= threshold)
+ continue;
+ goodix_milan_transform_compose (
+ pivot_to_reference, slot->values + 1, candidate_to_reference);
+ if (goodix_milan_relation_matrix_store_reference (
+ matrix, candidate, candidate_to_reference) != 0)
+ return -1;
+ active[candidate] = 1;
+ }
+ return 0;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/enrollment/propagation.h b/libfprint/drivers/goodix53x5/milan/enrollment/propagation.h
new file mode 100644
index 0000000..0664e67
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/enrollment/propagation.h
@@ -0,0 +1,50 @@
+/*
+ * Goodix 53x5 driver for libfprint - enrollment relation propagation
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include "milan/relations.h"
+
+typedef int (*GoodixMilanEnrollmentOverlapFunc) (void *user_data,
+ size_t first,
+ size_t second,
+ int32_t *overlap);
+
+GoodixMilanRelationSlot *
+goodix_milan_enrollment_relation_slot (GoodixMilanRelationMatrix *matrix,
+ size_t first,
+ size_t second);
+
+int
+goodix_milan_enrollment_feature_to_reference (
+ GoodixMilanRelationMatrix *matrix,
+ size_t feature,
+ int32_t transform[6]);
+
+int
+goodix_milan_enrollment_propagate_lower (
+ GoodixMilanRelationMatrix *matrix,
+ int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ size_t pivot,
+ const int32_t pivot_to_reference[6],
+ int32_t threshold,
+ GoodixMilanEnrollmentOverlapFunc overlap_func,
+ void *user_data);
+
+int
+goodix_milan_enrollment_propagate_higher (
+ GoodixMilanRelationMatrix *matrix,
+ int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ size_t pivot,
+ size_t current,
+ const int32_t pivot_to_reference[6],
+ int32_t threshold,
+ GoodixMilanEnrollmentOverlapFunc overlap_func,
+ void *user_data);
diff --git a/libfprint/drivers/goodix53x5/milan/enrollment/template.c b/libfprint/drivers/goodix53x5/milan/enrollment/template.c
new file mode 100644
index 0000000..5f76940
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/enrollment/template.c
@@ -0,0 +1,1299 @@
+/*
+ * Goodix 53x5 driver for libfprint - native Milan enrollment templates
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "milan/enrollment/propagation.h"
+#include "milan/match/match.h"
+#include "milan/match/info-private.h"
+#include "milan/milan.h"
+#include "milan/relations.h"
+#include "milan/study/policy.h"
+#include "milan/transform-private.h"
+
+#include <string.h>
+
+GBytes *
+goodix_milan_match_serialize_template (GoodixMatchInfo *info)
+{
+ return info && info->template ? g_bytes_ref (info->template) : NULL;
+}
+
+#define GOODIX_MILAN_ENROLLMENT_RECORD_CAPACITY 150
+
+typedef struct
+{
+ gboolean populated;
+ GoodixMilanFeatureBitmaps bitmaps;
+ guint8 inline_mask[72];
+ GoodixMilanFeatureRecord records[GOODIX_MILAN_ENROLLMENT_RECORD_CAPACITY];
+ guint32 record_count;
+ GoodixMilanAntifakeBlob antifake;
+ GoodixMilanFeatureTemplateFields fields;
+ gint32 neighbor_count;
+} GoodixMilanEnrollmentFeature;
+
+struct _GoodixMilanEnrollmentTransaction
+{
+ GoodixMilanEnrollmentFeature features[GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT];
+ GoodixMilanRelationMatrix matrix;
+ guint feature_count;
+ guint registration_count;
+ guint32 sensor_type;
+ gint32 graph_companion_f3;
+ gint32 graph_companion_f4;
+ guint32 queue_state;
+ guint32 queue_transaction_counter;
+ guint8 tail_state[0x520];
+};
+
+static void
+goodix_milan_match_set_feature_scalar (guint8 *element,
+ size_t element_size,
+ size_t field,
+ gint32 value)
+{
+ guint32 little_endian = GUINT32_TO_LE ((guint32) value);
+ size_t optional_size = element_size >= 5 && element[element_size - 5] == 0xc7 ?
+ 5 :
+ 0;
+
+ memcpy (element + element_size - 54 - optional_size + field * 5,
+ &little_endian,
+ sizeof (little_endian));
+}
+
+static void
+goodix_enrollment_feature_view (const GoodixMilanEnrollmentFeature *feature,
+ GoodixMilanFeatureView *view)
+{
+ memset (view, 0, sizeof (*view));
+ view->high_bitmap = feature->bitmaps.high_bitmap;
+ view->enhanced_bitmap = feature->bitmaps.enhanced_bitmap;
+ view->inline_mask = feature->inline_mask;
+ view->low_bitmap = feature->bitmaps.low_bitmap;
+ view->antifake = &feature->antifake;
+ view->record_count = feature->record_count;
+ view->fields = feature->fields;
+}
+
+static gboolean
+goodix_enrollment_feature_load (
+ GoodixMilanEnrollmentTransaction *transaction,
+ guint slot,
+ GBytes *probe_template)
+{
+ g_autofree GoodixMilanUnpackedTemplate *unpacked = NULL;
+ GoodixMilanEnrollmentFeature *feature;
+ GoodixMilanFeatureView view;
+ const guint8 *data;
+ gsize size;
+ gint32 retained_bb;
+ gint32 retained_neighbor_count;
+
+ if (!transaction || !probe_template ||
+ slot >= GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT)
+ return FALSE;
+ data = g_bytes_get_data (probe_template, &size);
+ unpacked = g_try_new0 (GoodixMilanUnpackedTemplate, 1);
+ if (!unpacked || size > GOODIX_MILAN_TEMPLATE_MAX_SIZE ||
+ goodix_milan_template_unpack (data, size, unpacked) != 0 ||
+ unpacked->feature_count != 1 ||
+ goodix_milan_template_parse_feature_element (
+ unpacked->feature_elements[0], unpacked->feature_element_sizes[0],
+ &view) != 0 ||
+ view.record_count > GOODIX_MILAN_ENROLLMENT_RECORD_CAPACITY ||
+ view.fields.tagged_values[2] < 0 ||
+ (guint32) view.fields.tagged_values[2] > view.record_count)
+ return FALSE;
+
+ feature = &transaction->features[slot];
+ retained_bb = feature->fields.tagged_values[6];
+ retained_neighbor_count = feature->neighbor_count;
+ memcpy (feature->bitmaps.high_bitmap, view.high_bitmap,
+ sizeof (feature->bitmaps.high_bitmap));
+ memcpy (feature->bitmaps.enhanced_bitmap, view.enhanced_bitmap,
+ sizeof (feature->bitmaps.enhanced_bitmap));
+ memcpy (feature->bitmaps.low_bitmap, view.low_bitmap,
+ sizeof (feature->bitmaps.low_bitmap));
+ memcpy (feature->inline_mask, view.inline_mask,
+ sizeof (feature->inline_mask));
+ if (goodix_milan_feature_unpack_template_records (
+ view.packed_records, view.record_count,
+ (guint32) view.fields.tagged_values[2], feature->records,
+ G_N_ELEMENTS (feature->records)) != 0)
+ return FALSE;
+ memcpy (&feature->antifake, view.antifake, sizeof (feature->antifake));
+ feature->record_count = (guint32) view.record_count;
+ feature->fields = view.fields;
+ feature->fields.tagged_values[6] = retained_bb;
+ feature->neighbor_count = retained_neighbor_count;
+ feature->populated = TRUE;
+
+ if (slot == 0)
+ {
+ transaction->sensor_type = unpacked->metadata.sensor_type;
+ transaction->queue_state = unpacked->metadata.queue_state;
+ transaction->queue_transaction_counter =
+ unpacked->metadata.queue_transaction_counter;
+ memcpy (transaction->tail_state, unpacked->tail_state,
+ sizeof (transaction->tail_state));
+ }
+ else if (unpacked->metadata.sensor_type != transaction->sensor_type)
+ {
+ return FALSE;
+ }
+ return TRUE;
+}
+
+static GBytes *
+goodix_enrollment_feature_pack (
+ const GoodixMilanEnrollmentFeature *feature)
+{
+ gsize capacity;
+ gsize size = 0;
+ guint8 *packed;
+
+ if (!feature || !feature->populated)
+ return NULL;
+ capacity = 7945 + (gsize) feature->record_count * 32 +
+ (feature->fields.optional_c7 != 0 ? 5 : 0);
+ packed = g_try_malloc (capacity);
+ if (!packed || goodix_milan_template_pack_feature_element (
+ feature->bitmaps.high_bitmap, feature->bitmaps.enhanced_bitmap,
+ feature->inline_mask, feature->bitmaps.low_bitmap, feature->records,
+ feature->record_count, &feature->antifake, &feature->fields, packed,
+ capacity, &size) != 0)
+ {
+ g_free (packed);
+ return NULL;
+ }
+ return g_bytes_new_take (packed, size);
+}
+
+static void
+goodix_milan_match_update_antifake_score (GoodixMilanAntifakeBlob *antifake,
+ gint32 score)
+{
+ gint32 current = goodix_milan_antifake_pair_score (antifake);
+
+ if (current == -1)
+ {
+ current = score;
+ }
+ else
+ {
+ uint32_t sum = (uint32_t) current + (uint32_t) score;
+
+ current = goodix_milan_transform_s32 (sum) / 2;
+ }
+ goodix_milan_antifake_set_pair_score (antifake, current);
+}
+
+typedef struct
+{
+ GoodixMilanRelationMatrix *matrix;
+ const GoodixMilanFeatureView *views;
+} GoodixEnrollmentPropagationContext;
+
+static int
+goodix_enrollment_relation_overlap (
+ void *user_data,
+ size_t first,
+ size_t second,
+ int32_t *overlap)
+{
+ GoodixEnrollmentPropagationContext *context = user_data;
+ size_t high = MAX (first, second);
+ size_t low = MIN (first, second);
+ GoodixMilanRelationSlot *slot = goodix_milan_enrollment_relation_slot (
+ context->matrix, high, low);
+ int32_t coverage;
+ int32_t detail;
+ int32_t low_metrics[3];
+
+ if (!slot || slot->values[0] < 0 ||
+ goodix_milan_match_overlap_metrics (
+ &context->views[low], &context->views[high], slot->values + 1,
+ overlap, &coverage, &detail, low_metrics) != 0)
+ return -1;
+ return 0;
+}
+
+static int
+goodix_enrollment_propagate_lower (
+ GoodixMilanRelationMatrix *matrix,
+ const GoodixMilanFeatureView views[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ size_t pivot,
+ const int32_t pivot_to_reference[6])
+{
+ GoodixEnrollmentPropagationContext context = { matrix, views };
+
+ return goodix_milan_enrollment_propagate_lower (
+ matrix, active, pivot, pivot_to_reference, 205,
+ goodix_enrollment_relation_overlap, &context);
+}
+
+static int
+goodix_enrollment_propagate_higher (
+ GoodixMilanRelationMatrix *matrix,
+ const GoodixMilanFeatureView views[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ size_t pivot,
+ size_t current,
+ const int32_t pivot_to_reference[6])
+{
+ GoodixEnrollmentPropagationContext context = { matrix, views };
+
+ return goodix_milan_enrollment_propagate_higher (
+ matrix, active, pivot, current, pivot_to_reference, 205,
+ goodix_enrollment_relation_overlap, &context);
+}
+
+static int
+goodix_enrollment_bridge_feature (
+ GoodixMilanRelationMatrix *matrix,
+ const GoodixMilanFeatureView views[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ size_t current,
+ size_t pivot)
+{
+ GoodixMilanRelationSlot *direct = goodix_milan_enrollment_relation_slot (
+ matrix, current, pivot);
+ int32_t current_to_reference[6];
+ int32_t pivot_to_current[6];
+ int32_t pivot_to_reference[6];
+
+ if (!direct || direct->values[0] < 0 ||
+ goodix_milan_enrollment_feature_to_reference (
+ matrix, current, current_to_reference) != 0 ||
+ goodix_milan_transform_invert (
+ direct->values + 1, pivot_to_current) != 0)
+ return -1;
+ goodix_milan_transform_compose (
+ current_to_reference, pivot_to_current, pivot_to_reference);
+ if (goodix_milan_relation_matrix_store_reference (
+ matrix, pivot, pivot_to_reference) != 0)
+ return -1;
+ active[pivot] = TRUE;
+ if (goodix_enrollment_propagate_lower (
+ matrix, views, active, pivot, pivot_to_reference) != 0 ||
+ goodix_enrollment_propagate_higher (
+ matrix, views, active, pivot, current, pivot_to_reference) != 0)
+ return -1;
+ return 0;
+}
+
+static int32_t
+goodix_enrollment_residual_area (
+ GoodixMilanRelationMatrix *matrix,
+ const GoodixMilanFeatureView views[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ const int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ size_t current)
+{
+ uint8_t residual[GOODIX_MILAN_STUDY_MASK_SIZE];
+ int32_t current_to_reference[6];
+ int32_t residual_count = 0;
+
+ goodix_milan_study_policy_expand_mask (
+ views[current].inline_mask, residual);
+ if (goodix_milan_enrollment_feature_to_reference (
+ matrix, current, current_to_reference) != 0)
+ return -1;
+ for (size_t prior = 0; prior < current; prior++)
+ {
+ int32_t prior_to_reference[6];
+ int32_t reference_to_prior[6];
+ int32_t current_to_prior[6];
+
+ if (!active[prior] || views[prior].fields.tagged_values[5] == 5)
+ continue;
+ if (goodix_milan_enrollment_feature_to_reference (
+ matrix, prior, prior_to_reference) != 0 ||
+ goodix_milan_transform_invert (
+ prior_to_reference, reference_to_prior) != 0)
+ return -1;
+ goodix_milan_transform_compose (
+ reference_to_prior, current_to_reference, current_to_prior);
+ current_to_prior[2] = goodix_milan_transform_sar32 (
+ (uint32_t) current_to_prior[2], 1);
+ current_to_prior[5] = goodix_milan_transform_sar32 (
+ (uint32_t) current_to_prior[5], 1);
+ goodix_milan_study_policy_remove_footprint (
+ residual, current_to_prior);
+ }
+ for (size_t i = 0; i < sizeof (residual); i++)
+ residual_count += residual[i] != 0;
+ return residual_count < 20 ? 0 : residual_count * 4;
+}
+
+static int
+goodix_enrollment_metrics (
+ GoodixMilanRelationMatrix *matrix,
+ const GoodixMilanFeatureView views[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ const int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ const int accepted_priors[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ const int32_t accepted_overlaps[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ size_t current,
+ GoodixMilanEnrollmentResult *result)
+{
+ const int32_t total_area =
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS *
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS;
+ int32_t residual = total_area;
+
+ result->previous_overlap = 0;
+ for (size_t prior = current; prior-- > 0;)
+ {
+ GoodixMilanRelationSlot *slot;
+
+ if (views[prior].fields.tagged_values[5] == 5)
+ continue;
+ slot = goodix_milan_enrollment_relation_slot (matrix, current, prior);
+ if (!slot)
+ return -1;
+ if (slot->values[0] >= 6)
+ {
+ int32_t area = goodix_milan_study_policy_full_footprint_area (
+ slot->values + 1);
+
+ result->previous_overlap = 100 - (guint8)
+ ((total_area - area) * 100 / (total_area + 1));
+ }
+ break;
+ }
+
+ if (matrix->graph_established && active[current])
+ {
+ residual = goodix_enrollment_residual_area (
+ matrix, views, active, current);
+ if (residual < 0)
+ return -1;
+ }
+ else
+ {
+ for (size_t prior = 0; prior < current; prior++)
+ if (accepted_priors[prior] && accepted_overlaps[prior] > 205)
+ {
+ GoodixMilanRelationSlot *slot =
+ goodix_milan_enrollment_relation_slot (matrix, current, prior);
+ int32_t uncovered;
+
+ if (!slot)
+ return -1;
+ uncovered = total_area -
+ goodix_milan_study_policy_full_footprint_area (
+ slot->values + 1);
+ if (uncovered < residual)
+ residual = uncovered;
+ }
+ }
+ result->overlap = 100 - (guint8)
+ (residual * 100 / (total_area + 1));
+ return 0;
+}
+
+GBytes *
+goodix_milan_match_combine_templates (GPtrArray *templates)
+{
+ GoodixMilanUnpackedTemplate *unpacked = NULL;
+ GoodixMilanRelationMatrix *relation_matrix = NULL;
+ const guint8 *elements[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY];
+ guint8 *element_copies[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+ GoodixMilanAntifakeBlob *mutable_antifakes[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY];
+ size_t element_sizes[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY];
+ GoodixMilanFeatureView feature_views[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY];
+ GoodixMilanTemplateRelation relations[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY];
+ int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+ size_t relation_count = 0;
+ GoodixMilanTemplateMetadata metadata = { 0 };
+ guint8 tail_state[0x520] = { 0 };
+ guint8 *combined = NULL;
+ guint8 *normalized = NULL;
+ size_t combined_capacity = 1433;
+ size_t combined_size = 0;
+ size_t normalized_size = 0;
+ GBytes *result = NULL;
+
+ if (!templates || templates->len == 0 ||
+ templates->len > GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT)
+ return NULL;
+ unpacked = g_new0 (GoodixMilanUnpackedTemplate, 1);
+ relation_matrix = g_new0 (GoodixMilanRelationMatrix, 1);
+ for (guint i = 0; i < templates->len; i++)
+ {
+ GBytes *template_bytes = g_ptr_array_index (templates, i);
+ gsize template_size;
+ const guint8 *template_data = g_bytes_get_data (
+ template_bytes, &template_size);
+
+ if (template_size > GOODIX_MILAN_TEMPLATE_MAX_SIZE ||
+ goodix_milan_template_unpack (
+ template_data, template_size, unpacked) != 0 ||
+ unpacked->feature_count != 1)
+ goto out;
+ element_sizes[i] = unpacked->feature_element_sizes[0];
+ if (element_sizes[i] < 55 ||
+ element_sizes[i] > GOODIX_MILAN_TEMPLATE_MAX_SIZE - combined_capacity)
+ goto out;
+ element_copies[i] = g_memdup2 (
+ unpacked->feature_elements[0], element_sizes[i]);
+ elements[i] = element_copies[i];
+ mutable_antifakes[i] = goodix_milan_template_mutable_feature_antifake (
+ element_copies[i], element_sizes[i]);
+ if (!mutable_antifakes[i] ||
+ goodix_milan_template_parse_feature_element (
+ element_copies[i], element_sizes[i], &feature_views[i]) != 0)
+ goto out;
+ relation_matrix->row_bases[i] =
+ goodix_milan_relation_matrix_expected_row_base (i);
+ if (i == 0)
+ {
+ metadata.sensor_type = unpacked->metadata.sensor_type;
+ memcpy (tail_state, unpacked->tail_state, sizeof (tail_state));
+ }
+ else if (unpacked->metadata.sensor_type != metadata.sensor_type)
+ {
+ goto out;
+ }
+ combined_capacity += element_sizes[i];
+ }
+ relation_matrix->feature_count = templates->len;
+ relation_matrix->reference_feature_index = SIZE_MAX;
+ for (size_t i = 0; i < GOODIX_MILAN_TEMPLATE_RELATION_CAPACITY; i++)
+ goodix_milan_relation_slot_unset (&relation_matrix->slots[i]);
+ metadata.maximum_features = GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT;
+ metadata.registration_count = 1;
+ metadata.maximum_records = 150;
+ metadata.graph_reference_index = -1;
+ metadata.graph_companion_f3 = -1;
+ metadata.graph_companion_f4 = -1;
+ memset (tail_state, 0xff, 200);
+ for (guint i = 0; i < templates->len; i++)
+ {
+ goodix_milan_match_set_feature_scalar (
+ element_copies[i], element_sizes[i], 1,
+ (gint32) metadata.registration_count);
+ goodix_milan_match_set_feature_scalar (
+ element_copies[i], element_sizes[i], 7, (gint32) i);
+ memcpy (tail_state + i * 4, &i, sizeof (i));
+ if (i == 0)
+ {
+ goodix_milan_match_set_feature_scalar (
+ element_copies[i], element_sizes[i], 1, 0);
+ continue;
+ }
+
+ GoodixMilanFeatureView current_view;
+ GoodixMilanFeatureRecord current_records[150];
+ int accepted_priors[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+ int32_t accepted_overlaps[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+ int32_t best_inliers = -1;
+ int32_t best_connected_inliers = -1;
+ guint best_prior = 0;
+ guint best_connected_prior = 0;
+
+ current_view = feature_views[i];
+ if (goodix_milan_feature_unpack_template_records (
+ current_view.packed_records, current_view.record_count,
+ current_view.fields.tagged_values[2], current_records, 150) != 0)
+ goto out;
+ for (guint prior = 0; prior < i; prior++)
+ {
+ GoodixMilanFeatureView prior_view;
+ GoodixMilanFeatureRecord prior_records[150];
+ GoodixMilanTemplateRelation candidate;
+ int32_t registration_detail;
+ int32_t registration_coverage;
+
+ prior_view = feature_views[prior];
+ if (goodix_milan_feature_unpack_template_records (
+ prior_view.packed_records, prior_view.record_count,
+ prior_view.fields.tagged_values[2], prior_records, 150) != 0)
+ goto out;
+ if (goodix_milan_estimate_relation (
+ prior_records, prior_view.record_count, current_records,
+ current_view.record_count,
+ (int32_t) metadata.registration_count + prior,
+ &candidate) != 0)
+ continue;
+ if (goodix_milan_registration_gate_metrics (
+ &prior_view, ¤t_view, candidate.values + 1,
+ ®istration_detail, ®istration_coverage) != 0)
+ continue;
+ int accepted = candidate.values[0] > 10 ||
+ (candidate.values[0] > 5 && registration_detail > 215) ||
+ (candidate.values[0] > 6 && registration_detail > 208 &&
+ registration_coverage > 64);
+
+ if (!accepted)
+ continue;
+ int32_t expected_index = relation_matrix->row_bases[i] + prior;
+
+ if (candidate.index != expected_index || expected_index < 1 ||
+ expected_index > GOODIX_MILAN_TEMPLATE_RELATION_CAPACITY)
+ goto out;
+ memcpy (relation_matrix->slots[expected_index - 1].values,
+ candidate.values, sizeof (candidate.values));
+ accepted_priors[prior] = TRUE;
+ GoodixEnrollmentPropagationContext context = {
+ relation_matrix, feature_views
+ };
+
+ if (goodix_enrollment_relation_overlap (
+ &context, i, prior,
+ &accepted_overlaps[prior]) != 0)
+ goto out;
+ if (active[prior] &&
+ candidate.values[0] > best_connected_inliers)
+ {
+ best_connected_inliers = candidate.values[0];
+ best_connected_prior = prior;
+ }
+ if (prior_view.fields.tagged_values[4] > 40 &&
+ current_view.fields.tagged_values[4] > 40)
+ {
+ gint32 pair_metrics[5];
+
+ if (goodix_milan_antifake_pair_metrics (
+ prior_view.antifake, GOODIX_MILAN_ANTIFAKE_SIZE,
+ current_view.antifake, GOODIX_MILAN_ANTIFAKE_SIZE,
+ candidate.values + 1, pair_metrics) != 0)
+ goto out;
+ if (pair_metrics[1] != 0)
+ {
+ goodix_milan_match_update_antifake_score (
+ mutable_antifakes[prior], pair_metrics[4]);
+ goodix_milan_match_update_antifake_score (
+ mutable_antifakes[i], pair_metrics[4]);
+ }
+ }
+ if (candidate.values[0] > best_inliers)
+ {
+ best_inliers = candidate.values[0];
+ best_prior = prior;
+ }
+ }
+ if (!relation_matrix->graph_established && best_inliers > 5 &&
+ accepted_overlaps[best_prior] > 205)
+ {
+ active[i] = TRUE;
+ active[best_prior] = TRUE;
+ relation_matrix->reference_feature_index = best_prior;
+ relation_matrix->graph_established = 1;
+ metadata.graph_reference_index = (gint32) best_prior;
+ metadata.graph_established = 1;
+ }
+ else if (best_connected_inliers >= 0)
+ {
+ GoodixMilanRelationSlot *direct =
+ goodix_milan_enrollment_relation_slot (
+ relation_matrix, i, best_connected_prior);
+ GoodixMilanRelationSlot *reference_slot =
+ goodix_milan_enrollment_relation_slot (
+ relation_matrix, i,
+ relation_matrix->reference_feature_index);
+ int32_t current_to_reference[6];
+
+ if (!direct || !reference_slot)
+ goto out;
+ if (best_connected_prior ==
+ relation_matrix->reference_feature_index)
+ {
+ memcpy (current_to_reference, direct->values + 1,
+ sizeof (current_to_reference));
+ }
+ else
+ {
+ GoodixMilanRelationSlot *connected =
+ goodix_milan_enrollment_relation_slot (
+ relation_matrix, best_connected_prior,
+ relation_matrix->reference_feature_index);
+
+ if (!connected || connected->values[0] < 0)
+ goto out;
+ goodix_milan_transform_route (
+ connected->values + 1, direct->values + 1,
+ (int32_t) best_connected_prior,
+ (int32_t) relation_matrix->reference_feature_index,
+ current_to_reference);
+ }
+ memcpy (reference_slot->values + 1, current_to_reference,
+ sizeof (current_to_reference));
+ if (reference_slot->values[0] < 0)
+ reference_slot->values[0] = 0;
+ active[i] = TRUE;
+ }
+ if (relation_matrix->graph_established && active[i])
+ {
+ int bridge_candidates[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+
+ for (guint prior = 0; prior < i; prior++)
+ bridge_candidates[prior] = accepted_priors[prior] && !active[prior];
+ for (guint prior = 0; prior < i; prior++)
+ if (bridge_candidates[prior] && accepted_overlaps[prior] > 208 &&
+ goodix_enrollment_bridge_feature (
+ relation_matrix, feature_views, active, i, prior) != 0)
+ goto out;
+ }
+ metadata.registration_count += i;
+ }
+ if (templates->len == GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT &&
+ goodix_milan_relation_matrix_close (relation_matrix, active) < 0)
+ goto out;
+ for (guint i = 0; i < templates->len; i++)
+ goodix_milan_match_set_feature_scalar (
+ element_copies[i], element_sizes[i], 0, active[i] ? 1 : 0);
+ if (goodix_milan_relation_matrix_project_reference_star (
+ relation_matrix, relations, G_N_ELEMENTS (relations),
+ &relation_count) != 0)
+ goto out;
+ if (relation_count >
+ (GOODIX_MILAN_TEMPLATE_MAX_SIZE - combined_capacity) / 45)
+ goto out;
+ combined_capacity += relation_count * 45;
+ combined = g_malloc (combined_capacity);
+ if (goodix_milan_template_pack (
+ elements, element_sizes, templates->len, relations, relation_count,
+ &metadata,
+ tail_state, sizeof (tail_state), combined, combined_capacity,
+ &combined_size) != 0)
+ goto out;
+ if (templates->len == GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT)
+ {
+ normalized = g_malloc (combined_capacity);
+ if (goodix_milan_template_normalize (
+ combined, combined_size, normalized, combined_capacity,
+ &normalized_size) != 0)
+ goto out;
+ result = g_bytes_new_take (normalized, normalized_size);
+ normalized = NULL;
+ }
+ else
+ {
+ result = g_bytes_new_take (combined, combined_size);
+ combined = NULL;
+ }
+
+out:
+ for (guint i = 0; i < GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY; i++)
+ g_free (element_copies[i]);
+ g_free (combined);
+ g_free (normalized);
+ g_free (relation_matrix);
+ g_free (unpacked);
+ return result;
+}
+
+GoodixMilanEnrollmentTransaction *
+goodix_milan_enrollment_transaction_new (void)
+{
+ GoodixMilanEnrollmentTransaction *transaction = g_try_new0 (
+ GoodixMilanEnrollmentTransaction, 1);
+
+ if (!transaction)
+ return NULL;
+ transaction->matrix.reference_feature_index = SIZE_MAX;
+ transaction->graph_companion_f3 = -1;
+ transaction->graph_companion_f4 = -1;
+ memset (transaction->tail_state, 0xff, 200);
+ for (guint i = 0; i < GOODIX_MILAN_TEMPLATE_RELATION_CAPACITY; i++)
+ goodix_milan_relation_slot_unset (&transaction->matrix.slots[i]);
+ return transaction;
+}
+
+void
+goodix_milan_enrollment_transaction_free (
+ GoodixMilanEnrollmentTransaction *transaction)
+{
+ g_free (transaction);
+}
+
+guint
+goodix_milan_enrollment_transaction_count (
+ const GoodixMilanEnrollmentTransaction *transaction)
+{
+ return transaction ? transaction->feature_count : 0;
+}
+
+static GoodixMilanEnrollmentTransaction *
+goodix_enrollment_transaction_clone (
+ const GoodixMilanEnrollmentTransaction *transaction)
+{
+ GoodixMilanEnrollmentTransaction *copy;
+
+ if (!transaction)
+ return NULL;
+ copy = g_try_malloc (sizeof (*copy));
+ if (copy)
+ memcpy (copy, transaction, sizeof (*copy));
+ return copy;
+}
+
+static void
+goodix_enrollment_transaction_views (
+ const GoodixMilanEnrollmentTransaction *transaction,
+ GoodixMilanFeatureView views[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY])
+{
+ memset (views, 0,
+ GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY * sizeof (*views));
+ memset (active, 0,
+ GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY * sizeof (*active));
+ for (guint i = 0; i < transaction->feature_count; i++)
+ {
+ goodix_enrollment_feature_view (&transaction->features[i], &views[i]);
+ active[i] = transaction->features[i].fields.tagged_values[0] == 1;
+ }
+}
+
+static gboolean
+goodix_enrollment_transaction_recompute_live_fields (
+ GoodixMilanEnrollmentTransaction *transaction)
+{
+ static const gint32 identity[6] = { 0x100, 0, 0, 0, 0x100, 0 };
+ GoodixMilanFeatureView views[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY];
+ int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY];
+ guint reference = transaction->matrix.reference_feature_index;
+
+ if (transaction->matrix.graph_established &&
+ reference >= transaction->feature_count)
+ return FALSE;
+
+ goodix_enrollment_transaction_views (transaction, views, active);
+ for (guint feature = 0; feature < transaction->feature_count; feature++)
+ {
+ GoodixMilanEnrollmentFeature *current = &transaction->features[feature];
+ guint8 residual[GOODIX_MILAN_STUDY_MASK_SIZE];
+ gint32 current_to_reference[6];
+ gint32 residual_count = 0;
+
+ current->neighbor_count = 0;
+ current->fields.tagged_values[6] = 52 * 44;
+ if (!active[feature])
+ continue;
+ if (goodix_milan_enrollment_feature_to_reference (
+ &transaction->matrix, feature, current_to_reference) != 0)
+ return FALSE;
+ goodix_milan_study_policy_expand_mask (current->inline_mask, residual);
+ for (guint other = 0; other < transaction->feature_count; other++)
+ {
+ GoodixMilanRelationSlot *slot;
+ gint32 reference_to_other[6];
+ gint32 current_to_other[6];
+
+ if (other == feature || !active[other])
+ continue;
+ if (other == reference)
+ {
+ memcpy (reference_to_other, identity, sizeof (identity));
+ }
+ else
+ {
+ slot = goodix_milan_enrollment_relation_slot (
+ &transaction->matrix, other, reference);
+ if (!slot || slot->values[0] < 0)
+ return FALSE;
+ if (reference < other)
+ {
+ if (goodix_milan_transform_invert (
+ slot->values + 1, reference_to_other) != 0)
+ return FALSE;
+ }
+ else
+ {
+ memcpy (reference_to_other, slot->values + 1,
+ sizeof (reference_to_other));
+ }
+ }
+ goodix_milan_transform_compose (
+ reference_to_other, current_to_reference, current_to_other);
+ current_to_other[2] = goodix_milan_transform_sar32 (
+ (guint32) current_to_other[2], 1);
+ current_to_other[5] = goodix_milan_transform_sar32 (
+ (guint32) current_to_other[5], 1);
+ if (goodix_milan_study_policy_footprint_area (current_to_other) * 100 >
+ 52 * 44 * 40)
+ current->neighbor_count++;
+ goodix_milan_study_policy_remove_footprint (
+ residual, current_to_other);
+ }
+ for (guint i = 0; i < G_N_ELEMENTS (residual); i++)
+ residual_count += residual[i] != 0;
+ current->fields.tagged_values[6] =
+ residual_count < 20 ? 0 : residual_count;
+ }
+ return TRUE;
+}
+
+static gboolean
+goodix_enrollment_transaction_insert (
+ GoodixMilanEnrollmentTransaction *transaction,
+ GBytes *probe_template,
+ GoodixMilanEnrollmentResult *result)
+{
+ GoodixMilanFeatureView views[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY];
+ int active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY];
+ guint current;
+ gint32 row_base;
+
+ if (!transaction || !probe_template || !result ||
+ transaction->feature_count >= GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT ||
+ transaction->matrix.feature_count != transaction->feature_count)
+ return FALSE;
+ current = transaction->feature_count;
+ row_base = goodix_milan_relation_matrix_expected_row_base (current);
+ if (!goodix_enrollment_feature_load (
+ transaction, current, probe_template) ||
+ goodix_milan_relation_matrix_append_row (
+ &transaction->matrix, row_base) != 0)
+ return FALSE;
+
+ transaction->features[current].fields.tagged_values[1] = row_base;
+ transaction->features[current].fields.tagged_values[5] = 0;
+ transaction->features[current].fields.tagged_values[7] = (gint32) current;
+ transaction->features[current].fields.tagged_values[8] = 0;
+ transaction->features[current].fields.tagged_values[9] = 0;
+ transaction->feature_count++;
+ transaction->registration_count = current == 0 ?
+ 1 : (guint) row_base + current;
+ goodix_enrollment_transaction_views (transaction, views, active);
+
+ if (current != 0)
+ {
+ int accepted_priors[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+ gint32 accepted_overlaps[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+ gint32 best_inliers = -1;
+ gint32 best_connected_inliers = -1;
+ guint best_prior = 0;
+ guint best_connected_prior = 0;
+
+ for (guint prior = 0; prior < current; prior++)
+ {
+ GoodixMilanTemplateRelation candidate;
+ GoodixMilanRelationSlot *slot;
+ gint32 registration_detail;
+ gint32 registration_coverage;
+
+ slot = goodix_milan_enrollment_relation_slot (
+ &transaction->matrix, current, prior);
+ if (!slot)
+ return FALSE;
+ goodix_milan_relation_slot_unset (slot);
+ if (goodix_milan_estimate_relation (
+ transaction->features[prior].records,
+ transaction->features[prior].record_count,
+ transaction->features[current].records,
+ transaction->features[current].record_count,
+ row_base + (gint32) prior, &candidate) != 0 ||
+ goodix_milan_registration_gate_metrics (
+ &views[prior], &views[current], candidate.values + 1,
+ ®istration_detail, ®istration_coverage) != 0)
+ continue;
+ if (!(candidate.values[0] > 10 ||
+ (candidate.values[0] > 5 && registration_detail > 215) ||
+ (candidate.values[0] > 6 && registration_detail > 208 &&
+ registration_coverage > 64)))
+ continue;
+
+ memcpy (slot->values, candidate.values, sizeof (slot->values));
+ accepted_priors[prior] = 1;
+ GoodixEnrollmentPropagationContext context = {
+ &transaction->matrix, views
+ };
+
+ if (goodix_enrollment_relation_overlap (
+ &context, current, prior, &accepted_overlaps[prior]) != 0)
+ return FALSE;
+ if (active[prior] &&
+ candidate.values[0] > best_connected_inliers)
+ {
+ best_connected_inliers = candidate.values[0];
+ best_connected_prior = prior;
+ }
+ if (transaction->features[prior].fields.tagged_values[4] > 40 &&
+ transaction->features[current].fields.tagged_values[4] > 40)
+ {
+ gint32 pair_metrics[5];
+
+ if (goodix_milan_antifake_pair_metrics (
+ &transaction->features[prior].antifake,
+ GOODIX_MILAN_ANTIFAKE_SIZE,
+ &transaction->features[current].antifake,
+ GOODIX_MILAN_ANTIFAKE_SIZE, candidate.values + 1,
+ pair_metrics) != 0)
+ return FALSE;
+ /* Native leaves both scores untouched when no mutual pair exists. */
+ if (pair_metrics[1] != 0)
+ {
+ goodix_milan_match_update_antifake_score (
+ &transaction->features[prior].antifake, pair_metrics[4]);
+ goodix_milan_match_update_antifake_score (
+ &transaction->features[current].antifake, pair_metrics[4]);
+ }
+ }
+ if (candidate.values[0] > best_inliers)
+ {
+ best_inliers = candidate.values[0];
+ best_prior = prior;
+ }
+ }
+
+ if (!transaction->matrix.graph_established && best_inliers > 5 &&
+ accepted_overlaps[best_prior] > 205)
+ {
+ active[current] = 1;
+ active[best_prior] = 1;
+ transaction->matrix.reference_feature_index = best_prior;
+ transaction->matrix.graph_established = 1;
+ }
+ else if (best_connected_inliers >= 0)
+ {
+ GoodixMilanRelationSlot *direct =
+ goodix_milan_enrollment_relation_slot (
+ &transaction->matrix, current, best_connected_prior);
+ GoodixMilanRelationSlot *reference_slot =
+ goodix_milan_enrollment_relation_slot (
+ &transaction->matrix, current,
+ transaction->matrix.reference_feature_index);
+ gint32 current_to_reference[6];
+
+ if (!direct || !reference_slot)
+ return FALSE;
+ if (best_connected_prior ==
+ transaction->matrix.reference_feature_index)
+ {
+ memcpy (current_to_reference, direct->values + 1,
+ sizeof (current_to_reference));
+ }
+ else
+ {
+ GoodixMilanRelationSlot *connected =
+ goodix_milan_enrollment_relation_slot (
+ &transaction->matrix, best_connected_prior,
+ transaction->matrix.reference_feature_index);
+
+ if (!connected || connected->values[0] < 0)
+ return FALSE;
+ goodix_milan_transform_route (
+ connected->values + 1, direct->values + 1,
+ (gint32) best_connected_prior,
+ (gint32) transaction->matrix.reference_feature_index,
+ current_to_reference);
+ }
+ memcpy (reference_slot->values + 1, current_to_reference,
+ sizeof (current_to_reference));
+ if (reference_slot->values[0] < 0)
+ reference_slot->values[0] = 0;
+ active[current] = 1;
+ }
+ if (transaction->matrix.graph_established && active[current])
+ {
+ int bridge_candidates[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+
+ for (guint prior = 0; prior < current; prior++)
+ bridge_candidates[prior] = accepted_priors[prior] && !active[prior];
+ for (guint prior = 0; prior < current; prior++)
+ if (bridge_candidates[prior] && accepted_overlaps[prior] > 208 &&
+ goodix_enrollment_bridge_feature (
+ &transaction->matrix, views, active, current, prior) != 0)
+ return FALSE;
+ }
+
+ for (guint i = 0; i < transaction->feature_count; i++)
+ transaction->features[i].fields.tagged_values[0] = active[i] ? 1 : 0;
+ if (best_inliers >= 0 && goodix_enrollment_metrics (
+ &transaction->matrix, views, active, accepted_priors,
+ accepted_overlaps, current, result) != 0)
+ return FALSE;
+ }
+
+ for (guint i = 0; i < transaction->feature_count; i++)
+ memcpy (transaction->tail_state + i * sizeof (i), &i, sizeof (i));
+ for (guint i = transaction->feature_count;
+ i < GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT; i++)
+ memset (transaction->tail_state + i * sizeof (i), 0xff, sizeof (i));
+
+ if (transaction->feature_count == GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT)
+ {
+ int final_active[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+
+ for (guint i = 0; i < transaction->feature_count; i++)
+ final_active[i] =
+ transaction->features[i].fields.tagged_values[0] == 1;
+ if (goodix_milan_relation_matrix_close (
+ &transaction->matrix, final_active) < 0)
+ return FALSE;
+ for (guint i = 0; i < transaction->feature_count; i++)
+ transaction->features[i].fields.tagged_values[0] =
+ final_active[i] ? 1 : 0;
+ return goodix_enrollment_transaction_recompute_live_fields (transaction);
+ }
+ return TRUE;
+}
+
+static gboolean
+goodix_enrollment_transaction_delete_last (
+ GoodixMilanEnrollmentTransaction *transaction)
+{
+ GoodixMilanEnrollmentFeature *removed;
+ guint removed_index;
+ gint32 row_base;
+
+ if (!transaction || transaction->feature_count == 0 ||
+ transaction->matrix.feature_count != transaction->feature_count)
+ return FALSE;
+ removed_index = transaction->feature_count - 1;
+ removed = &transaction->features[removed_index];
+ row_base = removed->fields.tagged_values[1];
+ if (row_base < 0 || (guint) row_base > transaction->registration_count)
+ return FALSE;
+ for (guint index = MAX (1U, (guint) row_base);
+ index < transaction->registration_count; index++)
+ {
+ GoodixMilanRelationSlot *slot = goodix_milan_relation_matrix_slot (
+ &transaction->matrix, (gint32) index);
+
+ if (!slot)
+ return FALSE;
+ goodix_milan_relation_slot_unset (slot);
+ }
+ transaction->registration_count = (guint) row_base;
+ transaction->feature_count--;
+ transaction->matrix.feature_count--;
+ if (removed_index == transaction->matrix.reference_feature_index)
+ {
+ transaction->matrix.graph_established = 0;
+ for (guint i = 0; i < transaction->feature_count; i++)
+ transaction->features[i].fields.tagged_values[0] = 0;
+ }
+ return goodix_enrollment_transaction_recompute_live_fields (transaction);
+}
+
+static gboolean
+goodix_enrollment_policy_should_rollback (
+ const GoodixMilanEnrollmentResult *result,
+ guint bad_record_count,
+ guint bad_continue_count)
+{
+ guint post_insertion_count;
+
+ if (!result)
+ return FALSE;
+ post_insertion_count = result->pre_insertion_accepted_count + 1;
+ return result->pre_insertion_accepted_count > 2 &&
+ bad_record_count <= 4 && bad_continue_count <= 2 &&
+ result->overlap > 85 &&
+ (post_insertion_count < 7 || result->previous_overlap > 75);
+}
+
+static void
+goodix_enrollment_policy_commit_non_rollback (guint *bad_continue_count)
+{
+ if (*bad_continue_count < 3)
+ *bad_continue_count = 0;
+}
+
+static guint
+goodix_enrollment_policy_commit_rollback (guint *bad_record_count,
+ guint *bad_continue_count)
+{
+ static const guint details[] = { 2, 4, 1, 3 };
+ guint detail = details[*bad_record_count % G_N_ELEMENTS (details)];
+
+ (*bad_record_count)++;
+ (*bad_continue_count)++;
+ return detail;
+}
+
+GoodixMilanEnrollmentAttemptStatus
+goodix_milan_enrollment_transaction_attempt (
+ GoodixMilanEnrollmentTransaction **transaction,
+ GBytes *probe_template,
+ guint *bad_record_count,
+ guint *bad_continue_count,
+ GoodixMilanEnrollmentResult *result)
+{
+ GoodixMilanEnrollmentTransaction *tentative;
+
+ if (!transaction || !*transaction || !probe_template ||
+ !bad_record_count || !bad_continue_count || !result)
+ return GOODIX_MILAN_ENROLLMENT_RETRY_REMOVE;
+ memset (result, 0, sizeof (*result));
+ result->pre_insertion_accepted_count = (*transaction)->feature_count;
+ tentative = goodix_enrollment_transaction_clone (*transaction);
+ if (!tentative || !goodix_enrollment_transaction_insert (
+ tentative, probe_template, result))
+ {
+ goodix_milan_enrollment_transaction_free (tentative);
+ goodix_enrollment_policy_commit_non_rollback (bad_continue_count);
+ return GOODIX_MILAN_ENROLLMENT_RETRY_REMOVE;
+ }
+
+ if (goodix_enrollment_policy_should_rollback (
+ result, *bad_record_count, *bad_continue_count))
+ {
+ if (!goodix_enrollment_transaction_delete_last (tentative))
+ {
+ goodix_milan_enrollment_transaction_free (tentative);
+ goodix_enrollment_policy_commit_non_rollback (bad_continue_count);
+ return GOODIX_MILAN_ENROLLMENT_RETRY_REMOVE;
+ }
+ result->reject_detail = goodix_enrollment_policy_commit_rollback (
+ bad_record_count, bad_continue_count);
+ goodix_milan_enrollment_transaction_free (*transaction);
+ *transaction = tentative;
+ return GOODIX_MILAN_ENROLLMENT_RETRY_CENTER;
+ }
+
+ goodix_enrollment_policy_commit_non_rollback (bad_continue_count);
+ goodix_milan_enrollment_transaction_free (*transaction);
+ *transaction = tentative;
+ return GOODIX_MILAN_ENROLLMENT_ACCEPTED;
+}
+
+GBytes *
+goodix_milan_enrollment_transaction_publish (
+ const GoodixMilanEnrollmentTransaction *transaction)
+{
+ GBytes *feature_bytes[GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT] = { 0 };
+ const guint8 *elements[GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT];
+ gsize element_sizes[GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT];
+ GoodixMilanTemplateRelation relations[GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT];
+ GoodixMilanTemplateMetadata metadata = { 0 };
+ gsize relation_count = 0;
+ gsize capacity = 1433;
+ gsize packed_size = 0;
+ gsize normalized_size = 0;
+ guint8 *packed = NULL;
+ guint8 *normalized = NULL;
+ GBytes *result = NULL;
+
+ if (!transaction || transaction->feature_count == 0 ||
+ transaction->feature_count > GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT ||
+ transaction->matrix.feature_count != transaction->feature_count)
+ return NULL;
+ for (guint i = 0; i < transaction->feature_count; i++)
+ {
+ feature_bytes[i] = goodix_enrollment_feature_pack (
+ &transaction->features[i]);
+ if (!feature_bytes[i])
+ goto out;
+ elements[i] = g_bytes_get_data (feature_bytes[i], &element_sizes[i]);
+ if (element_sizes[i] > GOODIX_MILAN_TEMPLATE_MAX_SIZE - capacity)
+ goto out;
+ capacity += element_sizes[i];
+ }
+ if (goodix_milan_relation_matrix_project_reference_star (
+ &transaction->matrix, relations, G_N_ELEMENTS (relations),
+ &relation_count) != 0 ||
+ relation_count > (GOODIX_MILAN_TEMPLATE_MAX_SIZE - capacity) / 45)
+ goto out;
+ capacity += relation_count * 45;
+ packed = g_try_malloc (capacity);
+ if (!packed)
+ goto out;
+ metadata.sensor_type = transaction->sensor_type;
+ metadata.maximum_features = GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT;
+ metadata.registration_count = transaction->registration_count;
+ metadata.maximum_records = GOODIX_MILAN_ENROLLMENT_RECORD_CAPACITY;
+ metadata.queue_state = transaction->queue_state;
+ metadata.queue_transaction_counter = transaction->queue_transaction_counter;
+ metadata.graph_reference_index =
+ transaction->matrix.reference_feature_index == SIZE_MAX ?
+ -1 : (gint32) transaction->matrix.reference_feature_index;
+ metadata.graph_companion_f3 = transaction->graph_companion_f3;
+ metadata.graph_companion_f4 = transaction->graph_companion_f4;
+ metadata.graph_established = transaction->matrix.graph_established;
+ if (goodix_milan_template_pack (
+ elements, element_sizes, transaction->feature_count, relations,
+ relation_count, &metadata, transaction->tail_state,
+ sizeof (transaction->tail_state), packed, capacity, &packed_size) != 0)
+ goto out;
+ if (transaction->feature_count == GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT)
+ {
+ normalized = g_try_malloc (capacity);
+ if (!normalized || goodix_milan_template_normalize (
+ packed, packed_size, normalized, capacity, &normalized_size) != 0)
+ goto out;
+ result = g_bytes_new_take (normalized, normalized_size);
+ normalized = NULL;
+ }
+ else
+ {
+ result = g_bytes_new_take (packed, packed_size);
+ packed = NULL;
+ }
+
+out:
+ for (guint i = 0; i < G_N_ELEMENTS (feature_bytes); i++)
+ g_clear_pointer (&feature_bytes[i], g_bytes_unref);
+ g_free (packed);
+ g_free (normalized);
+ return result;
+}
+
+#ifdef GOODIX53X5_DEBUG
+gboolean
+goodix_milan_enrollment_transaction_debug_state (
+ const GoodixMilanEnrollmentTransaction *transaction,
+ GoodixMilanEnrollmentDebugState *state)
+{
+ if (!transaction || !state)
+ return FALSE;
+ memset (state, 0, sizeof (*state));
+ state->feature_count = transaction->feature_count;
+ state->registration_count = transaction->registration_count;
+ state->graph_reference_index =
+ transaction->matrix.reference_feature_index == SIZE_MAX ?
+ -1 : (gint32) transaction->matrix.reference_feature_index;
+ state->graph_companion_f3 = transaction->graph_companion_f3;
+ state->graph_companion_f4 = transaction->graph_companion_f4;
+ state->graph_established = transaction->matrix.graph_established;
+ state->queue_state = transaction->queue_state;
+ state->queue_transaction_counter = transaction->queue_transaction_counter;
+ memcpy (state->order, transaction->tail_state, sizeof (state->order));
+ for (guint i = 0; i < GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT; i++)
+ {
+ state->slot_populated[i] = transaction->features[i].populated;
+ state->record_counts[i] = transaction->features[i].record_count;
+ memcpy (state->feature_fields[i],
+ transaction->features[i].fields.tagged_values,
+ sizeof (state->feature_fields[i]));
+ state->pair_scores[i] = goodix_milan_antifake_pair_score (
+ &transaction->features[i].antifake);
+ state->neighbor_counts[i] = transaction->features[i].neighbor_count;
+ }
+ memcpy (state->relations, transaction->matrix.slots,
+ sizeof (state->relations));
+ return TRUE;
+}
+
+gboolean
+goodix_milan_enrollment_transaction_debug_provisional (
+ const GoodixMilanEnrollmentTransaction *transaction,
+ GBytes *probe_template,
+ GoodixMilanEnrollmentResult *result,
+ GoodixMilanEnrollmentDebugState *state)
+{
+ g_autoptr(GoodixMilanEnrollmentTransaction) provisional = NULL;
+
+ if (!transaction || !probe_template || !result || !state)
+ return FALSE;
+ memset (result, 0, sizeof (*result));
+ result->pre_insertion_accepted_count = transaction->feature_count;
+ provisional = goodix_enrollment_transaction_clone (transaction);
+ return provisional && goodix_enrollment_transaction_insert (
+ provisional, probe_template, result) &&
+ goodix_milan_enrollment_transaction_debug_state (provisional, state);
+}
+#endif
diff --git a/libfprint/drivers/goodix53x5/milan/feature/enhancement.c b/libfprint/drivers/goodix53x5/milan/feature/enhancement.c
new file mode 100644
index 0000000..3090671
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/feature/enhancement.c
@@ -0,0 +1,418 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan feature enhancement
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/feature/feature.h"
+#include "milan/private.h"
+
+#include <stddef.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* Orientation extraction recovered from FUN_18007ebe0 and FUN_180074290. */
+enum {
+ MILAN_CORDIC_ITERATIONS = 13,
+ MILAN_ORIENTATION_PERIOD = 0x6488,
+ MILAN_ORIENTATION_HALF_PERIOD = 0x3244,
+ MILAN_ORIENTATION_QUARTER_PERIOD = 0x1922,
+ MILAN_ORIENTATION_DEGREE_SCALE = 0x1ca6,
+ MILAN_ORIENTATION_DEGREE_SHIFT = 20,
+ MILAN_ORIENTATION_SPLIT_DEGREES = 135,
+ MILAN_ORIENTATION_ROTATION_DEGREES = 45,
+ MILAN_ORIENTATION_BYTE_OFFSET = 76,
+ MILAN_ENHANCEMENT_DIRECTION_COUNT = 12,
+ MILAN_ENHANCEMENT_TAP_COUNT = 7,
+ MILAN_ENHANCEMENT_RADIUS = 6,
+ MILAN_ENHANCEMENT_DIRECTION_OFFSET = 8,
+ MILAN_ENHANCEMENT_DIRECTION_WIDTH = 15,
+ MILAN_ENHANCEMENT_DIRECTION_LIMIT = 165,
+ MILAN_BITMAP_HISTOGRAM_BINS = 256,
+ MILAN_BITMAP_SAMPLE_STRIDE = 2,
+ MILAN_BITMAP_QUANTILE_Q8 = 205,
+ MILAN_Q8_HALF = 128,
+ MILAN_Q8_SHIFT = 8,
+};
+
+int16_t
+feature_atan2 (int32_t y, int32_t x)
+{
+ static const int16_t angles[MILAN_CORDIC_ITERATIONS] = {
+ 3217, 1899, 1003, 509, 256, 128, 64, 32, 16, 8, 4, 2, 1,
+ };
+ int32_t original_x = x;
+ int32_t original_y = y;
+ uint16_t angle = 0;
+
+ x = x > 0 ? x : -x;
+ y = y > 0 ? y : -y;
+ if (x == 0)
+ return original_y > 0 ? 0 : MILAN_ORIENTATION_HALF_PERIOD;
+ if (y == 0)
+ return original_x > 0 ? MILAN_ORIENTATION_QUARTER_PERIOD :
+ -MILAN_ORIENTATION_QUARTER_PERIOD;
+
+ for (size_t i = 0; i < MILAN_CORDIC_ITERATIONS; i++)
+ {
+ int32_t shifted_x = x >> i;
+ int32_t shifted_y = y >> i;
+
+ if (x <= 0)
+ {
+ x += shifted_y;
+ y -= shifted_x;
+ angle = (uint16_t) (angle - angles[i]);
+ }
+ else
+ {
+ x -= shifted_y;
+ y += shifted_x;
+ angle = (uint16_t) (angle + angles[i]);
+ }
+ if (x == 0)
+ break;
+ }
+
+ if (original_y <= 0)
+ return original_x > 0 ?
+ (int16_t) (MILAN_ORIENTATION_HALF_PERIOD - angle) :
+ (int16_t) (angle - MILAN_ORIENTATION_HALF_PERIOD);
+ if (original_x < 0)
+ return (int16_t) -angle;
+ return (int16_t) angle;
+}
+
+static uint32_t
+feature_integral_sum (const uint32_t *integral,
+ size_t columns,
+ size_t row,
+ size_t column,
+ size_t rows,
+ size_t radius)
+{
+ size_t first_column = column > radius ? column - radius : 1;
+ size_t last_column = column + radius < columns ? column + radius :
+ columns - 1;
+ size_t first_row = row > radius ? row - radius : 1;
+ size_t last_row = row + radius < rows ? row + radius : rows - 1;
+
+ if (first_column == 0)
+ first_column = 1;
+ if (first_row == 0)
+ first_row = 1;
+ return integral[last_row * columns + last_column] -
+ integral[(first_row - 1) * columns + last_column] -
+ integral[last_row * columns + first_column - 1] +
+ integral[(first_row - 1) * columns + first_column - 1];
+}
+
+int
+feature_build_dense_orientation (const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ size_t radius,
+ uint8_t *orientation)
+{
+ size_t count;
+ int32_t *first = NULL;
+ int32_t *second = NULL;
+ uint32_t *first_integral = NULL;
+ uint32_t *second_integral = NULL;
+ int result = -1;
+
+ if (!frame || !orientation || rows < 2 || columns < 2 ||
+ columns > SIZE_MAX / rows)
+ return -1;
+ count = rows * columns;
+ if (count > SIZE_MAX / sizeof (*first))
+ return -1;
+ first = calloc (count, sizeof (*first));
+ second = calloc (count, sizeof (*second));
+ first_integral = calloc (count, sizeof (*first_integral));
+ second_integral = calloc (count, sizeof (*second_integral));
+ if (!first || !second || !first_integral || !second_integral)
+ goto out;
+
+ for (size_t row = 1; row + 1 < rows; row++)
+ for (size_t column = 1; column + 1 < columns; column++)
+ {
+ size_t i = row * columns + column;
+ int32_t horizontal =
+ ((int32_t) frame[i + 1] - frame[i - 1]) * 2 -
+ frame[i - columns - 1] - frame[i + columns - 1] +
+ frame[i - columns + 1] + frame[i + columns + 1];
+ int32_t vertical =
+ ((int32_t) frame[i + columns] - frame[i - columns]) * 2 -
+ frame[i - columns - 1] - frame[i - columns + 1] +
+ frame[i + columns - 1] + frame[i + columns + 1];
+
+ first[i] = horizontal * vertical * 2;
+ second[i] = horizontal * horizontal - vertical * vertical;
+ }
+ for (size_t row = 1; row < rows; row++)
+ for (size_t column = 1; column < columns; column++)
+ {
+ size_t i = row * columns + column;
+
+ first_integral[i] = (uint32_t) first[i] -
+ first_integral[i - columns - 1] +
+ first_integral[i - 1] +
+ first_integral[i - columns];
+ second_integral[i] = (uint32_t) second[i] -
+ second_integral[i - columns - 1] +
+ second_integral[i - 1] +
+ second_integral[i - columns];
+ }
+ for (size_t row = 0; row < rows; row++)
+ for (size_t column = 0; column < columns; column++)
+ {
+ int32_t y = (int32_t) feature_integral_sum (
+ first_integral, columns, row, column, rows, radius);
+ int32_t x = (int32_t) feature_integral_sum (
+ second_integral, columns, row, column, rows, radius);
+ int32_t angle = feature_atan2 (y, x);
+ int32_t degrees;
+
+ if (angle < 0)
+ angle += MILAN_ORIENTATION_PERIOD;
+ degrees = angle * MILAN_ORIENTATION_DEGREE_SCALE >>
+ MILAN_ORIENTATION_DEGREE_SHIFT;
+ orientation[row * columns + column] =
+ (uint8_t) (-MILAN_ORIENTATION_BYTE_OFFSET -
+ (degrees <= MILAN_ORIENTATION_SPLIT_DEGREES ?
+ degrees + MILAN_ORIENTATION_ROTATION_DEGREES :
+ degrees - MILAN_ORIENTATION_SPLIT_DEGREES));
+ }
+ result = 0;
+
+out:
+ free (second_integral);
+ free (first_integral);
+ free (second);
+ free (first);
+ return result;
+}
+
+/* Smooth each pixel along the seven-tap line selected by its orientation;
+ * edge taps outside the image are omitted rather than reflected. */
+int
+goodix_milan_feature_enhance (const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ uint8_t *orientation,
+ uint8_t *output)
+{
+ static const int8_t
+ offsets[MILAN_ENHANCEMENT_DIRECTION_COUNT][MILAN_ENHANCEMENT_TAP_COUNT][2] = {
+ { {-3, 0}, {-2, 0}, {-1, 0}, {0, 0}, {1, 0}, {2, 0}, {3, 0} },
+ { {-3, -1}, {-2, -1}, {-1, 0}, {0, 0}, {1, 0}, {2, 1}, {3, 1} },
+ { {-3, -2}, {-2, -1}, {-1, -1}, {0, 0}, {1, 1}, {2, 1}, {3, 2} },
+ { {-3, -3}, {-2, -2}, {-1, -1}, {0, 0}, {1, 1}, {2, 2}, {3, 3} },
+ { {-2, -3}, {-1, -2}, {-1, -1}, {0, 0}, {1, 1}, {1, 2}, {2, 3} },
+ { {-1, -3}, {-1, -2}, { 0, -1}, {0, 0}, {0, 1}, {1, 2}, {1, 3} },
+ { { 0, -3}, { 0, -2}, { 0, -1}, {0, 0}, {0, 1}, {0, 2}, {0, 3} },
+ { {-1, 3}, {-1, 2}, { 0, 1}, {0, 0}, {0, -1}, {1, -2}, {1, -3} },
+ { {-2, 3}, {-1, 2}, {-1, 1}, {0, 0}, {1, -1}, {1, -2}, {2, -3} },
+ { {-3, 3}, {-2, 2}, {-1, 1}, {0, 0}, {1, -1}, {2, -2}, {3, -3} },
+ { {-3, 2}, {-2, 1}, {-1, 1}, {0, 0}, {1, -1}, {2, -1}, {3, -2} },
+ { {-3, 1}, {-2, 1}, {-1, 0}, {0, 0}, {1, 0}, {2, -1}, {3, -1} },
+ };
+ static const uint8_t weights[MILAN_ENHANCEMENT_TAP_COUNT] = {
+ 1, 2, 4, 8, 4, 2, 1,
+ };
+ size_t count;
+ int32_t *first = NULL;
+ int32_t *second = NULL;
+ uint32_t *first_integral = NULL;
+ uint32_t *second_integral = NULL;
+ int result = -1;
+
+ if (!frame || !orientation || !output || rows < 2 || columns < 2 ||
+ columns > SIZE_MAX / rows)
+ return -1;
+ count = rows * columns;
+ if (count > SIZE_MAX / sizeof (*first))
+ return -1;
+
+ first = calloc (count, sizeof (*first));
+ second = calloc (count, sizeof (*second));
+ first_integral = calloc (count, sizeof (*first_integral));
+ second_integral = calloc (count, sizeof (*second_integral));
+ if (!first || !second || !first_integral || !second_integral)
+ goto out;
+
+ for (size_t row = 1; row + 1 < rows; row++)
+ {
+ for (size_t column = 1; column + 1 < columns; column++)
+ {
+ size_t i = row * columns + column;
+ int32_t horizontal =
+ ((int32_t) frame[i + 1] - frame[i - 1]) * 2 -
+ frame[i - columns - 1] - frame[i + columns - 1] +
+ frame[i - columns + 1] + frame[i + columns + 1];
+ int32_t vertical =
+ ((int32_t) frame[i + columns] - frame[i - columns]) * 2 -
+ frame[i - columns - 1] - frame[i - columns + 1] +
+ frame[i + columns - 1] + frame[i + columns + 1];
+
+ first[i] = horizontal * vertical * 2;
+ second[i] = horizontal * horizontal - vertical * vertical;
+ }
+ }
+
+ for (size_t row = 1; row < rows; row++)
+ {
+ for (size_t column = 1; column < columns; column++)
+ {
+ size_t i = row * columns + column;
+
+ first_integral[i] = (uint32_t) first[i] -
+ first_integral[i - columns - 1] +
+ first_integral[i - 1] +
+ first_integral[i - columns];
+ second_integral[i] = (uint32_t) second[i] -
+ second_integral[i - columns - 1] +
+ second_integral[i - 1] +
+ second_integral[i - columns];
+ }
+ }
+
+ for (size_t row = 0; row < rows; row++)
+ {
+ for (size_t column = 0; column < columns; column++)
+ {
+ int32_t y = (int32_t) feature_integral_sum (
+ first_integral, columns, row, column, rows,
+ MILAN_ENHANCEMENT_RADIUS);
+ int32_t x = (int32_t) feature_integral_sum (
+ second_integral, columns, row, column, rows,
+ MILAN_ENHANCEMENT_RADIUS);
+ int32_t angle = feature_atan2 (y, x);
+ int32_t degrees;
+
+ if (angle < 0)
+ angle += MILAN_ORIENTATION_PERIOD;
+ degrees = angle * MILAN_ORIENTATION_DEGREE_SCALE >>
+ MILAN_ORIENTATION_DEGREE_SHIFT;
+ orientation[row * columns + column] =
+ (uint8_t) (-MILAN_ORIENTATION_BYTE_OFFSET -
+ (degrees <= MILAN_ORIENTATION_SPLIT_DEGREES ?
+ degrees + MILAN_ORIENTATION_ROTATION_DEGREES :
+ degrees - MILAN_ORIENTATION_SPLIT_DEGREES));
+ }
+ }
+
+ for (size_t row = 0; row < rows; row++)
+ {
+ for (size_t column = 0; column < columns; column++)
+ {
+ size_t i = row * columns + column;
+ uint8_t shifted =
+ (uint8_t) (orientation[i] - MILAN_ENHANCEMENT_DIRECTION_OFFSET);
+ size_t direction = shifted < MILAN_ENHANCEMENT_DIRECTION_LIMIT ?
+ shifted / MILAN_ENHANCEMENT_DIRECTION_WIDTH + 1 :
+ 0;
+ uint32_t sum = 0;
+ uint32_t weight_sum = 0;
+
+ for (size_t tap = 0; tap < MILAN_ENHANCEMENT_TAP_COUNT; tap++)
+ {
+ ptrdiff_t x = (ptrdiff_t) column + offsets[direction][tap][0];
+ ptrdiff_t y = (ptrdiff_t) row + offsets[direction][tap][1];
+
+ if (x >= 0 && x < (ptrdiff_t) columns &&
+ y >= 0 && y < (ptrdiff_t) rows)
+ {
+ sum += frame[(size_t) y * columns + (size_t) x] * weights[tap];
+ weight_sum += weights[tap];
+ }
+ }
+ output[i] = weight_sum != 0 ? (uint8_t) (sum / weight_sum) : UINT8_MAX;
+ }
+ }
+ result = 0;
+
+out:
+ free (second_integral);
+ free (first_integral);
+ free (second);
+ free (first);
+ return result;
+}
+
+/* Select the masked even/even quantile, then pack every sample strictly above
+ * it; the feature mask affects threshold selection but does not gate bits. */
+int
+goodix_milan_feature_enhanced_bitmap (
+ const uint8_t *enhanced,
+ const uint8_t *feature_mask,
+ size_t rows,
+ size_t columns,
+ uint8_t *bitmap,
+ uint8_t *threshold)
+{
+ uint32_t histogram[MILAN_BITMAP_HISTOGRAM_BINS] = { 0 };
+ size_t map_rows;
+ size_t map_columns;
+ size_t map_count;
+ uint32_t active_count = 0;
+ uint32_t target;
+ uint8_t selected = 0;
+
+ if (!enhanced || !feature_mask || !bitmap || !threshold || rows < 2 ||
+ columns < 2 || columns > SIZE_MAX / rows)
+ return -1;
+ map_rows = rows / MILAN_BITMAP_SAMPLE_STRIDE;
+ map_columns = columns / MILAN_BITMAP_SAMPLE_STRIDE;
+ if (map_columns > SIZE_MAX / map_rows)
+ return -1;
+ map_count = map_rows * map_columns;
+
+ for (size_t row = 0; row < map_rows; row++)
+ for (size_t column = 0; column < map_columns; column++)
+ {
+ size_t map_index = row * map_columns + column;
+
+ if (feature_mask[map_index] != 0)
+ {
+ histogram[enhanced[row * MILAN_BITMAP_SAMPLE_STRIDE * columns +
+ column * MILAN_BITMAP_SAMPLE_STRIDE]]++;
+ active_count++;
+ }
+ }
+
+ target = (MILAN_BITMAP_QUANTILE_Q8 * active_count + MILAN_Q8_HALF) >>
+ MILAN_Q8_SHIFT;
+ for (size_t value = 1; value < MILAN_BITMAP_HISTOGRAM_BINS; value++)
+ {
+ histogram[value] += histogram[value - 1];
+ if (target <= histogram[value])
+ {
+ /* Bin zero can already exceed target; native distances are signed. */
+ selected = (int32_t) (histogram[value] - target) <=
+ (int32_t) (target - histogram[value - 1]) ?
+ (uint8_t) value :
+ (uint8_t) (value - 1);
+ break;
+ }
+ }
+ *threshold = selected;
+
+ memset (bitmap, 0, (map_count + 7) / 8);
+ for (size_t row = 0; row < map_rows; row++)
+ for (size_t column = 0; column < map_columns; column++)
+ {
+ size_t map_index = row * map_columns + column;
+
+ if (enhanced[row * MILAN_BITMAP_SAMPLE_STRIDE * columns +
+ column * MILAN_BITMAP_SAMPLE_STRIDE] > selected)
+ bitmap[map_index >> 3] |= (uint8_t) (1U << (map_index & 7));
+ }
+ return 0;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/feature/extraction.c b/libfprint/drivers/goodix53x5/milan/feature/extraction.c
new file mode 100644
index 0000000..32c22e0
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/feature/extraction.c
@@ -0,0 +1,572 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan feature extraction
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/feature/feature.h"
+#include "milan/private.h"
+
+#include <stddef.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+typedef struct
+{
+ size_t length;
+ uint16_t coefficients[15];
+} MilanFeatureKernel;
+
+static const MilanFeatureKernel milan_feature_kernels[2][6] = {
+ {
+ { 9, { 84, 957, 5433, 15399, 21790, 15399, 5433, 957, 84 } },
+ { 7, { 139, 2672, 15742, 28430, 15742, 2672, 139 } },
+ { 9, { 58, 791, 5088, 15549, 22564, 15549, 5088, 791, 58 } },
+ { 11, { 51, 420, 2169, 7008, 14165, 17910, 14165, 7008, 2169,
+ 420, 51 } },
+ { 13, { 70, 353, 1337, 3761, 7873, 12265, 14218, 12265, 7873,
+ 3761, 1337, 353, 70 } },
+ { 15, { 118, 396, 1102, 2547, 4886, 7783, 10289, 11294, 10289,
+ 7783, 4886, 2547, 1102, 396, 118 } },
+ },
+ {
+ { 9, { 54, 757, 5011, 15578, 22736, 15578, 5011, 757, 54 } },
+ { 7, { 90, 2260, 15585, 29666, 15585, 2260, 90 } },
+ { 9, { 36, 612, 4651, 15697, 23544, 15697, 4651, 612, 36 } },
+ { 11, { 31, 314, 1876, 6727, 14476, 18688, 14476, 6727, 1876,
+ 314, 31 } },
+ { 13, { 45, 266, 1130, 3486, 7794, 12630, 14834, 12630, 7794,
+ 3486, 1130, 266, 45 } },
+ { 15, { 82, 306, 934, 2327, 4731, 7853, 10645, 11780, 10645,
+ 7853, 4731, 2327, 934, 306, 82 } },
+ },
+};
+
+static int32_t
+feature_u32_as_s32 (uint32_t value)
+{
+ if (value <= INT32_MAX)
+ return (int32_t) value;
+ return -1 - (int32_t) (UINT32_MAX - value);
+}
+
+static int
+feature_filter_q16 (const uint16_t *source,
+ size_t rows,
+ size_t columns,
+ const MilanFeatureKernel *kernel,
+ uint16_t *output)
+{
+ size_t count = rows * columns;
+ size_t radius = kernel->length / 2;
+ uint16_t *horizontal = malloc (count * sizeof(*horizontal));
+
+ if (!horizontal)
+ return -1;
+ for (size_t column = 0; rows != 0 && column < columns; column++)
+ {
+ size_t reflected[15];
+
+ for (size_t tap = 0; tap < kernel->length; tap++)
+ reflected[tap] = goodix_milan_reflect101_index (
+ (ptrdiff_t) column + (ptrdiff_t) tap - (ptrdiff_t) radius,
+ columns);
+ for (size_t row = 0; row < rows; row++)
+ {
+ uint64_t sum = 0;
+
+ for (size_t tap = 0; tap < kernel->length; tap++)
+ sum += (uint64_t) source[row * columns + reflected[tap]] *
+ kernel->coefficients[tap];
+ horizontal[row * columns + column] = (uint16_t) (sum >> 16);
+ }
+ }
+ for (size_t row = 0; columns != 0 && row < rows; row++)
+ {
+ size_t reflected[15];
+
+ for (size_t tap = 0; tap < kernel->length; tap++)
+ reflected[tap] = goodix_milan_reflect101_index (
+ (ptrdiff_t) row + (ptrdiff_t) tap - (ptrdiff_t) radius, rows) *
+ columns;
+ for (size_t column = 0; column < columns; column++)
+ {
+ uint64_t sum = 0;
+
+ for (size_t tap = 0; tap < kernel->length; tap++)
+ sum += (uint64_t) horizontal[reflected[tap] + column] *
+ kernel->coefficients[tap];
+ output[row * columns + column] = (uint16_t) (sum >> 16);
+ }
+ }
+ free (horizontal);
+ return 0;
+}
+
+uint16_t
+feature_cordic (int32_t vertical,
+ int32_t *horizontal)
+{
+ static const uint16_t angles[13] = {
+ 0x0c91, 0x076b, 0x03eb, 0x01fd, 0x0100, 0x0080, 0x0040,
+ 0x0020, 0x0010, 0x0008, 0x0004, 0x0002, 0x0001,
+ };
+ static const int32_t gains[13] = {
+ 0xb505, 0xa1e9, 0x9d13, 0x9bdd, 0x9b8f, 0x9b7b, 0x9b77,
+ 0x9b75, 0x9b75, 0x9b75, 0x9b75, 0x9b75, 0x9b75,
+ };
+ int32_t original_horizontal = *horizontal;
+ int32_t original_vertical = vertical;
+ int32_t x = original_horizontal > 0 ? original_horizontal
+ : -original_horizontal;
+ int32_t y = original_vertical > 0 ? original_vertical : -original_vertical;
+ uint16_t angle = 0;
+ size_t stop = 12;
+
+ if (y == 0)
+ {
+ *horizontal = x;
+ return original_horizontal > 0 ? 0 : 0x3244;
+ }
+ if (x == 0)
+ {
+ *horizontal = y;
+ return original_vertical > 0 ? 0x1922 : 0xe6de;
+ }
+ for (size_t iteration = 0; iteration < 13; iteration++)
+ {
+ int32_t shifted_y = y >> iteration;
+ int32_t shifted_x = x >> iteration;
+
+ if (y > 0)
+ {
+ x += shifted_y;
+ y -= shifted_x;
+ angle = (uint16_t) (angle + angles[iteration]);
+ }
+ else
+ {
+ x -= shifted_y;
+ y += shifted_x;
+ angle = (uint16_t) (angle - angles[iteration]);
+ }
+ if (y == 0)
+ {
+ stop = iteration;
+ break;
+ }
+ }
+ if (original_horizontal > 0)
+ {
+ if (original_vertical < 0)
+ angle = (uint16_t) -angle;
+ }
+ else if (original_vertical > 0)
+ angle = (uint16_t) (0x3244 - angle);
+ else
+ angle = (uint16_t) (angle + 0xcdbc);
+ *horizontal = (int32_t) (((int64_t) gains[stop] * x + 0x8000) >> 16);
+ return angle;
+}
+
+static int
+feature_build_scale_space_pass (const uint8_t *blurred,
+ size_t rows,
+ size_t columns,
+ unsigned int pass_marker,
+ uint16_t *scales)
+{
+ const MilanFeatureKernel *kernels;
+ size_t count;
+
+ if ((rows != 0 && columns > SIZE_MAX / rows) ||
+ (pass_marker != 0 && pass_marker != 100))
+ return -1;
+ kernels = milan_feature_kernels[pass_marker == 100];
+ count = rows * columns;
+ uint16_t *source = malloc (count * sizeof(*source));
+ if (!source)
+ return -1;
+ for (size_t i = 0; i < count; i++)
+ source[i] = (uint16_t) blurred[i] << 8;
+ if (feature_filter_q16 (source, rows, columns, &kernels[0], scales) != 0)
+ {
+ free (source);
+ return -1;
+ }
+ free (source);
+ for (size_t scale = 1; scale < 6; scale++)
+ if (feature_filter_q16 (scales + (scale - 1) * count, rows, columns,
+ &kernels[scale],
+ scales + scale * count) != 0)
+ return -1;
+ return 0;
+}
+
+static int
+feature_build_gradients_pass (const uint8_t *enhanced,
+ size_t rows,
+ size_t columns,
+ unsigned int pass_marker,
+ int32_t *gradient_input,
+ uint32_t *magnitude,
+ int16_t *orientation)
+{
+ const MilanFeatureKernel *kernels;
+ size_t count;
+ uint16_t *lifted = NULL;
+ uint16_t *first = NULL;
+ uint16_t *second = NULL;
+ int result = -1;
+
+ if ((rows != 0 && columns > SIZE_MAX / rows) ||
+ (pass_marker != 0 && pass_marker != 100))
+ return -1;
+ kernels = milan_feature_kernels[pass_marker == 100];
+ count = rows * columns;
+ lifted = malloc (count * sizeof(*lifted));
+ first = malloc (count * sizeof(*first));
+ second = malloc (count * sizeof(*second));
+ if (!lifted || !first || !second)
+ goto out;
+ for (size_t i = 0; i < count; i++)
+ lifted[i] = (uint16_t) enhanced[i] << 8;
+ if (feature_filter_q16 (lifted, rows, columns, &kernels[0], first) != 0 ||
+ feature_filter_q16 (first, rows, columns, &kernels[1], second) != 0)
+ goto out;
+ for (size_t i = 0; i < count; i++)
+ gradient_input[i] = (int32_t) first[i] * 10 - (int32_t) second[i] * 9;
+ memset (magnitude, 0, count * sizeof(*magnitude));
+ memset (orientation, 0, count * sizeof(*orientation));
+ for (size_t row = 1; row + 1 < rows; row++)
+ for (size_t column = 1; column + 1 < columns; column++)
+ {
+ size_t i = row * columns + column;
+ int32_t horizontal = gradient_input[i + 1] - gradient_input[i - 1];
+ int32_t vertical = gradient_input[i + columns] -
+ gradient_input[i - columns];
+
+ if (horizontal > 0x7ffff)
+ horizontal = 0x7ffff;
+ else if (horizontal < -0x80000)
+ horizontal = -0x80000;
+ if (vertical > 0x7ffff)
+ vertical = 0x7ffff;
+ else if (vertical < -0x80000)
+ vertical = -0x80000;
+ horizontal = feature_u32_as_s32 ((uint32_t) horizontal << 12);
+ vertical = feature_u32_as_s32 ((uint32_t) vertical << 12);
+ orientation[i] = (int16_t) feature_cordic (vertical, &horizontal);
+ magnitude[i] = (uint32_t) (horizontal >> 12);
+ if (magnitude[i] > 0x3ffff)
+ magnitude[i] = 0x3ffff;
+ }
+ result = 0;
+
+out:
+ free (second);
+ free (first);
+ free (lifted);
+ return result;
+}
+
+static int
+feature_gaussian6_u8 (const uint8_t *source,
+ size_t rows,
+ size_t columns,
+ uint8_t *output)
+{
+ static const MilanFeatureKernel kernel = {
+ 3, { 21845, 21845, 21845 },
+ };
+ size_t count;
+ uint16_t *lifted = NULL;
+ uint16_t *filtered = NULL;
+
+ if (rows == 0 || columns == 0 || columns > SIZE_MAX / rows ||
+ rows * columns > SIZE_MAX / sizeof(*lifted))
+ return -1;
+ count = rows * columns;
+ lifted = calloc (count, sizeof(*lifted));
+ filtered = calloc (count, sizeof(*filtered));
+
+ if (!lifted || !filtered)
+ {
+ free (filtered);
+ free (lifted);
+ return -1;
+ }
+ for (size_t i = 0; i < count; i++)
+ lifted[i] = (uint16_t) source[i] << 8;
+ int result = feature_filter_q16 (lifted, rows, columns, &kernel, filtered);
+ if (result == 0)
+ for (size_t i = 0; i < count; i++)
+ output[i] = (uint8_t) (filtered[i] >> 8);
+ free (filtered);
+ free (lifted);
+ return result;
+}
+
+int
+goodix_milan_feature_should_retry_scale_space (size_t materialized_count,
+ unsigned int pass_marker,
+ int configured_retry)
+{
+ return materialized_count <= 60 && pass_marker == 0 &&
+ configured_retry != 0;
+}
+
+static int
+feature_filter_broken_pixels (GoodixMilanFeatureRecord *records,
+ size_t *record_count,
+ const uint8_t *broken_mask,
+ size_t rows,
+ size_t columns,
+ uint8_t *validity_mask,
+ int high_class)
+{
+ size_t stride = columns + 1;
+ size_t radius = high_class < 4 ? 2 : 5;
+ int16_t *integral = calloc ((rows + 1) * stride, sizeof(*integral));
+ uint16_t *local_zeros = calloc (rows * columns, sizeof(*local_zeros));
+ int global_zeros = 0;
+ int result = -1;
+
+ if (!integral || !local_zeros)
+ goto out;
+ for (size_t y = 0; y < rows; y++)
+ for (size_t x = 0; x < columns; x++)
+ {
+ size_t source = y * columns + x;
+ size_t destination = (y + 1) * stride + x + 1;
+ int zero = broken_mask[source] == 0;
+
+ global_zeros += zero;
+ integral[destination] = (int16_t) (
+ integral[destination - stride] + integral[destination - 1] -
+ integral[destination - stride - 1] + zero);
+ }
+ if (global_zeros >= 50)
+ {
+ for (size_t y = 0; y < rows; y++)
+ for (size_t x = 0; x < columns; x++)
+ {
+ size_t left = x > radius ? x - radius : 0;
+ size_t top = y > radius ? y - radius : 0;
+ size_t right = x + radius + 1 < columns
+ ? x + radius + 1
+ : columns;
+ size_t bottom = y + radius + 1 < rows ? y + radius + 1 : rows;
+
+ local_zeros[y * columns + x] = (uint16_t) (
+ integral[bottom * stride + right] -
+ integral[top * stride + right] -
+ integral[bottom * stride + left] +
+ integral[top * stride + left]);
+ }
+ if (high_class >= 4)
+ {
+ size_t validity_columns = columns / 8 * 8;
+
+ for (size_t y = 0; y < rows; y++)
+ for (size_t x = 0; x < validity_columns; x++)
+ if (local_zeros[y * columns + x] != 0)
+ validity_mask[y * validity_columns + x] = 0;
+ }
+ for (size_t i = 0; i < *record_count;)
+ {
+ size_t x = ((uint16_t) records[i].refined_x + 0x80) >> 8;
+ size_t y = ((uint16_t) records[i].refined_y + 0x80) >> 8;
+
+ /* Native checks only x before indexing the unshifted 108-wide map. */
+ if (x < columns && local_zeros[y * columns + x] > 1)
+ {
+ (*record_count)--;
+ if (i != *record_count)
+ {
+ records[i] = records[*record_count];
+ memset (&records[*record_count], 0,
+ sizeof(records[*record_count]));
+ }
+ continue;
+ }
+ i++;
+ }
+ }
+ result = 0;
+
+out:
+ free (local_zeros);
+ free (integral);
+ return result;
+}
+
+static int
+feature_extract_records (
+ const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureRecord *records,
+ size_t capacity,
+ size_t *record_count,
+ size_t *zero_flag_count,
+ int expand_records,
+ int configured_retry,
+ const uint8_t *broken_mask,
+ uint8_t *validity_mask,
+ int high_class)
+{
+ GoodixMilanFeatureRecord
+ materialized[MILAN_FEATURE_MATERIALIZED_LIMIT];
+ GoodixMilanFeatureRank ranks[MILAN_FEATURE_MATERIALIZED_LIMIT];
+ GoodixMilanFeatureAux auxiliary[MILAN_FEATURE_MATERIALIZED_LIMIT];
+ size_t cropped_columns;
+ size_t count;
+ size_t materialized_count;
+ size_t offset;
+ unsigned int pass_marker = 0;
+ uint8_t *cropped = NULL;
+ uint8_t *dense_orientation = NULL;
+ uint8_t *enhanced = NULL;
+ uint8_t *blurred = NULL;
+ uint16_t *scales = NULL;
+ int32_t *gradient_input = NULL;
+ uint32_t *magnitude = NULL;
+ int16_t *gradient_orientation = NULL;
+ int result = -1;
+
+ if (!frame || !records || !record_count || !zero_flag_count || rows < 2 ||
+ columns < 8 || columns > SIZE_MAX / rows)
+ return -1;
+ cropped_columns = columns / 8 * 8;
+ count = rows * cropped_columns;
+ offset = (columns - cropped_columns) / 2;
+ cropped = malloc (count);
+ dense_orientation = malloc (count);
+ enhanced = malloc (count);
+ blurred = malloc (count);
+ scales = malloc (6 * count * sizeof(*scales));
+ gradient_input = malloc (count * sizeof(*gradient_input));
+ magnitude = malloc (count * sizeof(*magnitude));
+ gradient_orientation = malloc (count * sizeof(*gradient_orientation));
+ if (!cropped || !dense_orientation || !enhanced || !blurred ||
+ !scales || !gradient_input || !magnitude ||
+ !gradient_orientation)
+ goto out;
+ for (size_t row = 0; row < rows; row++)
+ memcpy (cropped + row * cropped_columns,
+ frame + row * columns + offset, cropped_columns);
+ if (goodix_milan_feature_enhance (
+ cropped, rows, cropped_columns, dense_orientation, enhanced) != 0 ||
+ feature_gaussian6_u8 (
+ cropped, rows, cropped_columns, blurred) != 0 ||
+ feature_build_gradients_pass (
+ enhanced, rows, cropped_columns, pass_marker, gradient_input,
+ magnitude, gradient_orientation) != 0 ||
+ feature_build_scale_space_pass (
+ blurred, rows, cropped_columns, pass_marker, scales) != 0)
+ goto out;
+
+ materialized_count = goodix_milan_feature_collect_materialized (
+ blurred, scales, magnitude, gradient_orientation, rows, cropped_columns,
+ materialized, ranks, auxiliary, MILAN_FEATURE_MATERIALIZED_LIMIT);
+ if (goodix_milan_feature_should_retry_scale_space (
+ materialized_count, pass_marker, configured_retry))
+ {
+ pass_marker = 100;
+ if (feature_build_scale_space_pass (
+ blurred, rows, cropped_columns, pass_marker, scales) != 0)
+ goto out;
+ if (feature_build_gradients_pass (
+ enhanced, rows, cropped_columns, pass_marker, gradient_input,
+ magnitude, gradient_orientation) != 0)
+ goto out;
+ materialized_count = goodix_milan_feature_collect_materialized (
+ blurred, scales, magnitude, gradient_orientation, rows,
+ cropped_columns, materialized, ranks, auxiliary,
+ MILAN_FEATURE_MATERIALIZED_LIMIT);
+ }
+ size_t limit = capacity < 150 ? capacity : 150;
+ *record_count = feature_finish_pretransform_records (
+ magnitude, gradient_orientation, rows, cropped_columns, records, limit,
+ materialized, ranks, auxiliary, materialized_count);
+ if (broken_mask && *record_count != 0 &&
+ feature_filter_broken_pixels (
+ records, record_count, broken_mask, rows, columns, validity_mask,
+ high_class) != 0)
+ goto out;
+ for (size_t i = 0; i < *record_count; i++)
+ goodix_milan_feature_transform_record ((uint8_t *) &records[i],
+ expand_records);
+ *zero_flag_count = goodix_milan_feature_partition_records (
+ (uint8_t *) records, *record_count);
+ result = 0;
+
+out:
+ free (gradient_orientation);
+ free (magnitude);
+ free (gradient_input);
+ free (scales);
+ free (blurred);
+ free (enhanced);
+ free (dense_orientation);
+ free (cropped);
+ return result;
+}
+
+int
+goodix_milan_feature_extract_records_mode_configured (
+ const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureRecord *records,
+ size_t capacity,
+ size_t *record_count,
+ size_t *zero_flag_count,
+ int expand_records,
+ int configured_retry)
+{
+ return feature_extract_records (
+ frame, rows, columns, records, capacity, record_count, zero_flag_count,
+ expand_records, configured_retry, NULL, NULL, 0);
+}
+
+int
+goodix_milan_feature_extract_records_mode_masked (
+ const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureRecord *records,
+ size_t capacity,
+ size_t *record_count,
+ size_t *zero_flag_count,
+ int expand_records,
+ const uint8_t *broken_mask,
+ uint8_t *validity_mask,
+ int high_class)
+{
+ return feature_extract_records (
+ frame, rows, columns, records, capacity, record_count, zero_flag_count,
+ expand_records, 1, broken_mask, validity_mask, high_class);
+}
+
+int
+goodix_milan_feature_extract_records_mode (
+ const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureRecord *records,
+ size_t capacity,
+ size_t *record_count,
+ size_t *zero_flag_count,
+ int expand_records)
+{
+ return goodix_milan_feature_extract_records_mode_configured (
+ frame, rows, columns, records, capacity, record_count, zero_flag_count,
+ expand_records, 1);
+}
diff --git a/libfprint/drivers/goodix53x5/milan/feature/extrema.c b/libfprint/drivers/goodix53x5/milan/feature/extrema.c
new file mode 100644
index 0000000..36ed2ed
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/feature/extrema.c
@@ -0,0 +1,405 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan feature extrema refinement
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/feature/feature.h"
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* Profile-9 extrema discovery and refinement recovered from FUN_180047c50,
+ * FUN_180048c60, FUN_18004bed0, FUN_18004c5a0, and FUN_18004c100. */
+enum {
+ AXIS_X,
+ AXIS_Y,
+ AXIS_SCALE,
+ AXIS_COUNT,
+};
+
+enum {
+ HESSIAN_XX,
+ HESSIAN_YY,
+ HESSIAN_SCALE_SCALE,
+ HESSIAN_XY,
+ HESSIAN_Y_SCALE,
+ HESSIAN_X_SCALE,
+ HESSIAN_COUNT,
+};
+
+#define EXTREMA_SCALE_LIMIT 4
+#define EXTREMA_RESPONSE_THRESHOLD 0x148
+#define DERIVATIVE_LIMIT 0x8000
+#define MIXED_DERIVATIVE_LIMIT 0x2000
+#define REFINEMENT_ATTEMPT_LIMIT 5
+#define REFINEMENT_Q12_SHIFT 12
+#define REFINEMENT_Q12_ONE (1 << REFINEMENT_Q12_SHIFT)
+#define REFINEMENT_Q12_HALF (REFINEMENT_Q12_ONE >> 1)
+#define REFINEMENT_Q12_TO_Q8_SHIFT 4
+#define REFINEMENT_OFFSET_SATURATION 0x00ffffff
+#define REFINEMENT_CONTRAST_SCALE 0x4000
+#define REFINEMENT_CONTRAST_MINIMUM 0x1478000
+#define REFINEMENT_EDGE_RATIO 40
+#define REFINEMENT_EDGE_RATIO_PLUS_ONE 41
+#define REFINEMENT_CURVATURE_SCALE 0x400
+#define REFINEMENT_SCALE_EXPONENT_FACTOR 0x10
+#define REFINEMENT_SCALE_EXPONENT_DIVISOR 3
+#define REFINEMENT_SCALE_FACTOR 0x13333
+#define REFINEMENT_Q16_SHIFT 16
+
+int
+feature_next_extremum (
+ const uint16_t *scales,
+ size_t rows,
+ size_t columns,
+ size_t cursor[3],
+ GoodixMilanFeatureExtremum *result)
+{
+ size_t count;
+
+ count = rows * columns;
+ for (size_t scale = cursor[0];
+ scale < EXTREMA_SCALE_LIMIT;
+ scale++, cursor[1] = EXTREMA_SCAN_BORDER)
+ for (size_t row = cursor[1];
+ row + EXTREMA_SCAN_BORDER < rows;
+ row++, cursor[2] = EXTREMA_SCAN_BORDER)
+ for (size_t column = cursor[2];
+ column + EXTREMA_SCAN_BORDER < columns;
+ column++)
+ {
+ size_t pixel = row * columns + column;
+ int32_t response = (int16_t) (
+ scales[(scale + 1) * count + pixel] -
+ scales[scale * count + pixel]);
+ int32_t absolute = response < 0 ? -response : response;
+ int extremum = absolute > EXTREMA_RESPONSE_THRESHOLD;
+
+ for (ptrdiff_t adjacent = -1; extremum && adjacent <= 1; adjacent++)
+ for (ptrdiff_t delta_row = -1;
+ extremum && delta_row <= 1;
+ delta_row++)
+ for (ptrdiff_t delta_column = -1; delta_column <= 1;
+ delta_column++)
+ {
+ if (adjacent == 0 && delta_row == 0 && delta_column == 0)
+ continue;
+ size_t neighbor =
+ (size_t) ((ptrdiff_t) row + delta_row) * columns +
+ (size_t) ((ptrdiff_t) column + delta_column);
+ size_t neighbor_scale =
+ (size_t) ((ptrdiff_t) scale + adjacent);
+ int32_t neighbor_response =
+ (int32_t) scales[(neighbor_scale + 1) * count + neighbor] -
+ (int32_t) scales[neighbor_scale * count + neighbor];
+
+ if ((response > 0 && neighbor_response > response) ||
+ (response < 0 && neighbor_response < response))
+ extremum = 0;
+ }
+ if (!extremum)
+ continue;
+ *result = (GoodixMilanFeatureExtremum){
+ (int32_t) column, (int32_t) row, (int32_t) scale, response,
+ };
+ cursor[0] = scale;
+ cursor[1] = row;
+ cursor[2] = column + 1;
+ return 1;
+ }
+ cursor[0] = EXTREMA_SCALE_LIMIT;
+ return 0;
+}
+
+size_t
+goodix_milan_feature_collect_extrema (
+ const uint16_t *scales,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureExtremum *extrema,
+ size_t capacity)
+{
+ size_t cursor[3] = FEATURE_EXTREMA_CURSOR_INIT;
+ GoodixMilanFeatureExtremum extremum;
+ size_t result_count = 0;
+
+ while (feature_next_extremum (scales, rows, columns, cursor, &extremum))
+ {
+ if (result_count < capacity && extrema)
+ extrema[result_count] = extremum;
+ result_count++;
+ }
+ return result_count;
+}
+
+static int
+feature_build_refinement_derivatives (const uint16_t *scales,
+ size_t rows,
+ size_t columns,
+ int32_t x,
+ int32_t y,
+ int32_t scale,
+ int16_t hessian[HESSIAN_COUNT],
+ int16_t gradient[AXIS_COUNT],
+ int16_t *center)
+{
+ size_t count = rows * columns;
+ size_t pixel = (size_t) y * columns + (size_t) x;
+ const uint16_t *previous = scales + (size_t) (scale - 1) * count;
+ const uint16_t *current = scales + (size_t) scale * count;
+ const uint16_t *next = scales + (size_t) (scale + 1) * count;
+ const uint16_t *next2 = scales + (size_t) (scale + 2) * count;
+ int32_t value;
+
+ *center = (int16_t) (2 * ((int32_t) next[pixel] - current[pixel]));
+ value = 2 * (((int32_t) current[pixel - 1] - next[pixel - 1]) -
+ current[pixel + 1] + next[pixel + 1]);
+ if (value <= -DERIVATIVE_LIMIT || value >= DERIVATIVE_LIMIT)
+ return 0;
+ gradient[AXIS_X] = (int16_t) value;
+ value = 2 * (((int32_t) current[pixel - columns] -
+ next[pixel - columns]) -
+ current[pixel + columns] + next[pixel + columns]);
+ if (value <= -DERIVATIVE_LIMIT || value >= DERIVATIVE_LIMIT)
+ return 0;
+ gradient[AXIS_Y] = (int16_t) value;
+ value = 2 * (((int32_t) previous[pixel] - current[pixel]) - next[pixel] +
+ next2[pixel]);
+ if (value <= -DERIVATIVE_LIMIT || value >= DERIVATIVE_LIMIT)
+ return 0;
+ gradient[AXIS_SCALE] = (int16_t) value;
+
+ value = 4 * (((int32_t) next[pixel - 1] - current[pixel - 1]) -
+ current[pixel + 1] - *center + next[pixel + 1]);
+ if (value <= -DERIVATIVE_LIMIT || value >= DERIVATIVE_LIMIT)
+ return 0;
+ hessian[HESSIAN_XX] = (int16_t) value;
+ value = 4 * (((int32_t) next[pixel - columns] -
+ current[pixel - columns]) -
+ *center - current[pixel + columns] + next[pixel + columns]);
+ if (value <= -DERIVATIVE_LIMIT || value >= DERIVATIVE_LIMIT)
+ return 0;
+ hessian[HESSIAN_YY] = (int16_t) value;
+ value = 4 * (((int32_t) current[pixel] - previous[pixel]) - next[pixel] -
+ *center + next2[pixel]);
+ if (value <= -DERIVATIVE_LIMIT || value >= DERIVATIVE_LIMIT)
+ return 0;
+ hessian[HESSIAN_SCALE_SCALE] = (int16_t) value;
+
+ value = ((int32_t) current[pixel + columns - 1] -
+ next[pixel + columns - 1]) -
+ next[pixel - columns + 1] - current[pixel + columns + 1] -
+ current[pixel - columns - 1] + current[pixel - columns + 1] +
+ next[pixel + columns + 1] + next[pixel - columns - 1];
+ if (value <= -MIXED_DERIVATIVE_LIMIT || value >= MIXED_DERIVATIVE_LIMIT)
+ return 0;
+ hessian[HESSIAN_XY] = (int16_t) value;
+ value = ((int32_t) previous[pixel + columns] -
+ previous[pixel - columns]) -
+ next2[pixel - columns] + next2[pixel + columns] -
+ next[pixel + columns] - current[pixel + columns] +
+ current[pixel - columns] + next[pixel - columns];
+ if (value <= -MIXED_DERIVATIVE_LIMIT || value >= MIXED_DERIVATIVE_LIMIT)
+ return 0;
+ hessian[HESSIAN_Y_SCALE] = (int16_t) value;
+ value = ((int32_t) previous[pixel + 1] - previous[pixel - 1]) -
+ next2[pixel - 1] + next2[pixel + 1] - current[pixel + 1] -
+ next[pixel + 1] + next[pixel - 1] + current[pixel - 1];
+ if (value <= -MIXED_DERIVATIVE_LIMIT || value >= MIXED_DERIVATIVE_LIMIT)
+ return 0;
+ hessian[HESSIAN_X_SCALE] = (int16_t) value;
+ return 1;
+}
+
+static int
+feature_signed_bit_length (int64_t value)
+{
+ uint64_t magnitude = value < 0 ? (uint64_t) -value : (uint64_t) value;
+ int length = 1;
+
+ while (magnitude != 0)
+ {
+ length++;
+ magnitude >>= 1;
+ }
+ return length;
+}
+
+static void
+feature_solve_refinement_offset (const int16_t hessian[HESSIAN_COUNT],
+ const int16_t gradient[AXIS_COUNT],
+ int32_t offset[AXIS_COUNT])
+{
+ int64_t h00 = hessian[HESSIAN_XX];
+ int64_t h11 = hessian[HESSIAN_YY];
+ int64_t h22 = hessian[HESSIAN_SCALE_SCALE];
+ int64_t h01 = hessian[HESSIAN_XY];
+ int64_t h12 = hessian[HESSIAN_Y_SCALE];
+ int64_t h02 = hessian[HESSIAN_X_SCALE];
+ int64_t cofactor0 = h11 * h22 - h12 * h12;
+ int64_t cofactor1 = h02 * h12 - h01 * h22;
+ int64_t cofactor2 = h01 * h12 - h02 * h11;
+ int64_t determinant = h00 * cofactor0 + h01 * cofactor1 +
+ h02 * cofactor2;
+ int64_t numerator[AXIS_COUNT];
+ int determinant_bits = feature_signed_bit_length (determinant);
+
+ if (determinant == 0)
+ {
+ memset (offset, 0, AXIS_COUNT * sizeof (*offset));
+ return;
+ }
+ numerator[AXIS_X] = -((int64_t) gradient[AXIS_X] * cofactor0 +
+ (int64_t) gradient[AXIS_Y] * cofactor1 +
+ (int64_t) gradient[AXIS_SCALE] * cofactor2);
+ numerator[AXIS_Y] =
+ -((h00 * h22 - h02 * h02) * gradient[AXIS_Y] +
+ (h01 * h02 - h00 * h12) * gradient[AXIS_SCALE] +
+ (int64_t) gradient[AXIS_X] * cofactor1);
+ numerator[AXIS_SCALE] =
+ -((h00 * h11 - h01 * h01) * gradient[AXIS_SCALE] +
+ (h01 * h02 - h00 * h12) * gradient[AXIS_Y] +
+ (int64_t) gradient[AXIS_X] * cofactor2);
+
+ for (size_t axis = 0; axis < AXIS_COUNT; axis++)
+ {
+ int numerator_bits = feature_signed_bit_length (numerator[axis]);
+ int64_t scaled_numerator = numerator[axis];
+ int64_t scaled_determinant = determinant;
+
+ if (numerator_bits - determinant_bits >= 9)
+ {
+ offset[axis] = REFINEMENT_OFFSET_SATURATION;
+ continue;
+ }
+ int bits = numerator_bits > determinant_bits ? numerator_bits :
+ determinant_bits;
+ if (bits > 32)
+ {
+ scaled_numerator >>= bits - 32;
+ scaled_determinant >>= bits - 32;
+ }
+ offset[axis] = (int32_t) ((scaled_numerator * REFINEMENT_Q12_ONE) /
+ scaled_determinant);
+ }
+}
+
+static int32_t
+feature_round_q12_move (int32_t value)
+{
+ if (value < 0)
+ {
+ uint32_t magnitude = (uint32_t) -value;
+ return -(int32_t) ((magnitude >> REFINEMENT_Q12_SHIFT) +
+ ((magnitude & REFINEMENT_Q12_HALF) != 0));
+ }
+ return (value >> REFINEMENT_Q12_SHIFT) +
+ (((uint32_t) value & REFINEMENT_Q12_HALF) != 0);
+}
+
+static uint32_t
+feature_exp2_q16 (int32_t value)
+{
+ static const uint32_t thresholds[16] = {
+ 0x95c0, 0x526a, 0x2b80, 0x1664, 0x0b5d, 0x05ba, 0x02e0, 0x0171,
+ 0x00b8, 0x005c, 0x002e, 0x0017, 0x000c, 0x0006, 0x0003, 0x0001,
+ };
+ uint32_t magnitude = value < 0 ? (uint32_t) -value : (uint32_t) value;
+ uint32_t fraction = magnitude & ((UINT32_C (1) << REFINEMENT_Q16_SHIFT) - 1);
+ uint64_t result = UINT64_C (1) << REFINEMENT_Q16_SHIFT;
+
+ if ((magnitude >> REFINEMENT_Q16_SHIFT) > 0)
+ result <<= magnitude >> REFINEMENT_Q16_SHIFT;
+ for (size_t bit = 0; bit < 16; bit++)
+ if (fraction >= thresholds[bit])
+ {
+ fraction -= thresholds[bit];
+ result += result >> (bit + 1);
+ }
+ return value > 0 ? (uint32_t) result :
+ (uint32_t) ((UINT64_C (1) << 32) / result);
+}
+
+int
+goodix_milan_feature_refine_extremum (
+ const uint16_t *scales,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureCandidate *candidate,
+ uint32_t *curvature)
+{
+ int16_t hessian[HESSIAN_COUNT];
+ int16_t gradient[AXIS_COUNT];
+ int16_t center;
+ int32_t offset[AXIS_COUNT];
+ int32_t x, y, scale;
+
+ x = candidate->x;
+ y = candidate->y;
+ scale = candidate->scale;
+ for (size_t iteration = 0; iteration < REFINEMENT_ATTEMPT_LIMIT; iteration++)
+ {
+ if (!feature_build_refinement_derivatives (
+ scales, rows, columns, x, y, scale, hessian, gradient, ¢er))
+ return 0;
+ feature_solve_refinement_offset (hessian, gradient, offset);
+ if (abs (offset[AXIS_X]) < REFINEMENT_Q12_HALF &&
+ abs (offset[AXIS_Y]) < REFINEMENT_Q12_HALF &&
+ abs (offset[AXIS_SCALE]) < REFINEMENT_Q12_HALF)
+ {
+ int64_t contrast = (int64_t) center * REFINEMENT_CONTRAST_SCALE +
+ (int64_t) gradient[AXIS_X] * offset[AXIS_X] +
+ (int64_t) gradient[AXIS_Y] * offset[AXIS_Y] +
+ (int64_t) gradient[AXIS_SCALE] * offset[AXIS_SCALE];
+ if (contrast <= 0)
+ contrast = -contrast;
+ if (contrast < REFINEMENT_CONTRAST_MINIMUM)
+ return 0;
+ candidate->strength =
+ (int32_t) (contrast >> REFINEMENT_Q12_SHIFT);
+ int32_t trace = (int32_t) hessian[HESSIAN_XX] + hessian[HESSIAN_YY];
+ int32_t determinant =
+ (int32_t) hessian[HESSIAN_XX] * hessian[HESSIAN_YY] -
+ (int32_t) hessian[HESSIAN_XY] * hessian[HESSIAN_XY];
+ if (determinant <= 0 ||
+ (int64_t) determinant * REFINEMENT_EDGE_RATIO_PLUS_ONE *
+ REFINEMENT_EDGE_RATIO_PLUS_ONE <=
+ (int64_t) REFINEMENT_EDGE_RATIO * trace * trace)
+ return 0;
+ candidate->refined_x =
+ (int16_t) ((x * REFINEMENT_Q12_ONE + offset[AXIS_X]) >>
+ REFINEMENT_Q12_TO_Q8_SHIFT);
+ candidate->refined_y =
+ (int16_t) ((y * REFINEMENT_Q12_ONE + offset[AXIS_Y]) >>
+ REFINEMENT_Q12_TO_Q8_SHIFT);
+ *curvature =
+ (uint32_t) (((int64_t) trace * trace *
+ REFINEMENT_CURVATURE_SCALE) / determinant);
+ int32_t exponent =
+ ((scale * REFINEMENT_Q12_ONE + offset[AXIS_SCALE]) *
+ REFINEMENT_SCALE_EXPONENT_FACTOR) /
+ REFINEMENT_SCALE_EXPONENT_DIVISOR;
+ candidate->scale_value =
+ (int32_t) (((uint64_t) feature_exp2_q16 (exponent) *
+ REFINEMENT_SCALE_FACTOR) >> REFINEMENT_Q16_SHIFT);
+ return 1;
+ }
+
+ x += feature_round_q12_move (offset[AXIS_X]);
+ y += feature_round_q12_move (offset[AXIS_Y]);
+ scale += feature_round_q12_move (offset[AXIS_SCALE]);
+ candidate->x = x;
+ candidate->y = y;
+ candidate->scale = scale;
+ if (scale < EXTREMA_FIRST_SCALE || scale >= EXTREMA_SCALE_LIMIT || x < 1 ||
+ x >= (int32_t) columns - 1 || y < 1 || y >= (int32_t) rows - 1)
+ return 0;
+ }
+ return 0;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/feature/feature.h b/libfprint/drivers/goodix53x5/milan/feature/feature.h
new file mode 100644
index 0000000..8434ba5
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/feature/feature.h
@@ -0,0 +1,158 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan feature extraction
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include <stddef.h>
+#include <stdint.h>
+
+int goodix_milan_feature_base_maps (const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ uint8_t *high_bitmap,
+ uint8_t *low_bitmap,
+ uint8_t *feature_mask,
+ uint8_t *inline_mask);
+
+int goodix_milan_feature_enhance (const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ uint8_t *orientation,
+ uint8_t *output);
+
+int goodix_milan_feature_enhanced_bitmap (const uint8_t *enhanced,
+ const uint8_t *feature_mask,
+ size_t rows,
+ size_t columns,
+ uint8_t *bitmap,
+ uint8_t *threshold);
+
+void goodix_milan_feature_transform_record (uint8_t *record,
+ int reverse_bits);
+
+size_t goodix_milan_feature_partition_records (uint8_t *records,
+ size_t record_count);
+
+typedef struct
+{
+ int32_t x;
+ int32_t y;
+ int32_t scale;
+ int32_t response;
+} GoodixMilanFeatureExtremum;
+
+#define EXTREMA_SCAN_BORDER 6
+#define EXTREMA_FIRST_SCALE 1
+#define FEATURE_EXTREMA_CURSOR_INIT \
+ { EXTREMA_FIRST_SCALE, EXTREMA_SCAN_BORDER, EXTREMA_SCAN_BORDER }
+
+/* Cursor order is scale, row, column. Keep the planes and dimensions unchanged
+ * between calls; a zero return leaves the cursor exhausted. */
+int feature_next_extremum (const uint16_t *scales,
+ size_t rows,
+ size_t columns,
+ size_t cursor[3],
+ GoodixMilanFeatureExtremum *extremum);
+
+size_t goodix_milan_feature_collect_extrema (const uint16_t *scales,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureExtremum *extrema,
+ size_t capacity);
+
+typedef struct
+{
+ int32_t x;
+ int32_t y;
+ int32_t scale;
+ int32_t strength;
+ int16_t refined_x;
+ int16_t refined_y;
+ int32_t scale_value;
+} GoodixMilanFeatureCandidate;
+
+int goodix_milan_feature_refine_extremum (const uint16_t *scales,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureCandidate *candidate,
+ uint32_t *curvature);
+
+typedef struct _GoodixMilanFeatureRecord GoodixMilanFeatureRecord;
+
+struct _GoodixMilanFeatureRecord
+{
+ uint16_t foreground;
+ int16_t refined_x;
+ int16_t refined_y;
+ int16_t orientation;
+ int32_t strength;
+ uint8_t payload[44];
+};
+
+typedef struct
+{
+ int32_t strength;
+ int32_t index;
+} GoodixMilanFeatureRank;
+
+typedef struct
+{
+ int32_t x;
+ int32_t y;
+ int32_t scale_value;
+ uint32_t peak;
+ uint32_t selected_peak;
+ uint16_t secondary_orientation;
+ uint16_t reserved;
+} GoodixMilanFeatureAux;
+
+size_t goodix_milan_feature_collect_materialized (const uint8_t *feature_source,
+ const uint16_t *scales,
+ const uint32_t *magnitude,
+ const int16_t *orientation,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureRecord *records,
+ GoodixMilanFeatureRank *ranks,
+ GoodixMilanFeatureAux *auxiliary,
+ size_t capacity);
+
+int goodix_milan_feature_should_retry_scale_space (size_t materialized_count,
+ unsigned int pass_marker,
+ int configured_retry);
+
+void goodix_milan_feature_build_descriptor_samples (int32_t center_x,
+ int32_t center_y,
+ int32_t descriptor_scale,
+ int16_t feature_orientation,
+ const uint32_t *magnitude,
+ const int16_t *orientation,
+ size_t rows,
+ size_t columns,
+ int32_t samples[128]);
+
+int goodix_milan_feature_extract_records_mode (const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureRecord *records,
+ size_t capacity,
+ size_t *record_count,
+ size_t *zero_flag_count,
+ int expand_records);
+
+int goodix_milan_feature_extract_records_mode_configured (const uint8_t *frame,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureRecord *records,
+ size_t capacity,
+ size_t *record_count,
+ size_t *zero_flag_count,
+ int expand_records,
+ int configured_retry);
diff --git a/libfprint/drivers/goodix53x5/milan/feature/mask.c b/libfprint/drivers/goodix53x5/milan/feature/mask.c
new file mode 100644
index 0000000..14e3549
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/feature/mask.c
@@ -0,0 +1,31 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan feature masks
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/feature/feature.h"
+#include "milan/private.h"
+
+#include <stdint.h>
+#include <string.h>
+
+void
+goodix_milan_feature_mask_expand (const uint8_t packed[72], uint8_t mask[44 * 52])
+{
+ for (size_t y = 0; y < 22; y++)
+ for (size_t x = 0; x < 26; x++)
+ {
+ size_t bit_index = y * 26 + x;
+ uint8_t value = (packed[bit_index / 8] >> (bit_index & 7)) & 1;
+
+ mask[(y * 2) * 52 + x * 2] = value;
+ mask[(y * 2) * 52 + x * 2 + 1] = value;
+ mask[(y * 2 + 1) * 52 + x * 2] = value;
+ mask[(y * 2 + 1) * 52 + x * 2 + 1] = value;
+ }
+}
diff --git a/libfprint/drivers/goodix53x5/milan/feature/materialization.c b/libfprint/drivers/goodix53x5/milan/feature/materialization.c
new file mode 100644
index 0000000..48b0b74
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/feature/materialization.c
@@ -0,0 +1,620 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan feature materialization
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/feature/feature.h"
+#include "milan/private.h"
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+static void
+feature_build_orientation_weights (uint32_t *weights,
+ size_t size,
+ uint32_t coefficient)
+{
+ for (size_t y = 0; y < size; y++)
+ for (size_t x = y; x < size; x++)
+ {
+ uint32_t radius_squared = (uint32_t) (x * x + y * y);
+ uint32_t power = radius_squared * coefficient;
+ uint32_t weight = 0;
+
+ if (power <= 0x6ee75)
+ {
+ uint32_t reduced = power >> 8;
+ uint32_t reduced_squared = reduced * reduced;
+ uint32_t approximation = reduced_squared >> 8;
+
+ approximation =
+ ((approximation * approximation >> 8) *
+ ((power / 5 + 0x10000) >> 8)) /
+ 0xc00 +
+ 0x200 +
+ (((power / 6 + 0x8000) >> 8) * reduced_squared >> 15) +
+ (power >> 7);
+ weight = ((approximation >> 1) + 0x40000) / approximation;
+ }
+ weights[y * size + x] = weight;
+ weights[x * size + y] = weight;
+ }
+}
+
+static uint32_t
+feature_build_orientation_histogram (int32_t center_x,
+ int32_t center_y,
+ int32_t scale_value,
+ const uint32_t *magnitude,
+ const int16_t *orientation,
+ size_t rows,
+ size_t columns,
+ uint32_t histogram[36],
+ int32_t *selected_bin)
+{
+ int32_t radius_q16 = (int32_t) ((uint32_t) scale_value * 18U) >> 2;
+ int32_t sigma_q16 = (int32_t) ((uint32_t) scale_value * 6U) >> 2;
+ uint32_t raw[36] = { 0 };
+ uint32_t extended[40];
+ uint32_t weights[33 * 33] = { 0 };
+ int32_t radius = radius_q16 < 0
+ ? -(((-radius_q16) >> 16) +
+ ((((uint32_t) -radius_q16) & 0x8000) != 0))
+ : (radius_q16 >> 16) +
+ (((uint32_t) radius_q16 & 0x8000) != 0);
+ radius = radius > 32 ? 32 : radius;
+ size_t size = (size_t) radius + 1;
+ uint32_t coefficient =
+ (uint32_t) (UINT64_C(0x800000000000) /
+ ((int64_t) sigma_q16 * sigma_q16));
+
+ feature_build_orientation_weights (weights, size, coefficient);
+ int32_t min_y = 1 - center_y > -radius ? 1 - center_y : -radius;
+ int32_t max_y = (int32_t) rows - center_y - 2 < radius
+ ? (int32_t) rows - center_y - 2
+ : radius;
+ int32_t min_x = 1 - center_x > -radius ? 1 - center_x : -radius;
+ int32_t max_x = (int32_t) columns - center_x - 2 < radius
+ ? (int32_t) columns - center_x - 2
+ : radius;
+
+ for (int32_t delta_y = min_y; delta_y <= max_y; delta_y++)
+ for (int32_t delta_x = min_x; delta_x <= max_x; delta_x++)
+ {
+ size_t pixel = (size_t) (center_y + delta_y) * columns +
+ (size_t) (center_x + delta_x);
+ int32_t bin = ((int32_t) orientation[pixel] * -36 + 0x743d4) /
+ 0x6488;
+ uint32_t weighted =
+ magnitude[pixel] *
+ weights[(size_t) abs (delta_y) * size + (size_t) abs (delta_x)] >> 8;
+
+ if (bin >= 36)
+ bin = 0;
+ raw[bin] += weighted;
+ raw[(bin + 18) % 36] += weighted;
+ }
+ extended[0] = raw[34];
+ extended[1] = raw[35];
+ memcpy (extended + 2, raw, sizeof(raw));
+ extended[38] = raw[0];
+ extended[39] = raw[1];
+ for (size_t bin = 0; bin < 36; bin++)
+ histogram[bin] = (extended[bin] + 4 * extended[bin + 1] +
+ 6 * extended[bin + 2] + 4 * extended[bin + 3] +
+ extended[bin + 4]) >>
+ 4;
+ uint32_t peak = histogram[0];
+ int32_t peak_bin = 0;
+ for (int32_t bin = 1; bin < 36; bin++)
+ if (histogram[bin] > peak)
+ {
+ peak = histogram[bin];
+ peak_bin = bin;
+ }
+ *selected_bin = peak_bin + 18;
+ return peak;
+}
+
+static void
+feature_materialize_candidate (const uint8_t *feature_source,
+ const uint32_t *magnitude,
+ const int16_t *orientation,
+ size_t rows,
+ size_t columns,
+ const GoodixMilanFeatureCandidate *candidate,
+ size_t index,
+ GoodixMilanFeatureRecord *record,
+ GoodixMilanFeatureRank *rank,
+ GoodixMilanFeatureAux *auxiliary)
+{
+ uint32_t histogram[36];
+ int32_t selected_bin;
+ uint32_t peak = feature_build_orientation_histogram (
+ candidate->x, candidate->y, candidate->scale_value, magnitude,
+ orientation, rows, columns, histogram, &selected_bin);
+ int32_t previous_bin = selected_bin == 0 ? 35 : selected_bin - 1;
+ int32_t next_bin = (selected_bin + 1) % 36;
+ int64_t previous = histogram[previous_bin];
+ int64_t current = histogram[selected_bin];
+ int64_t next = histogram[next_bin];
+ int64_t denominator = 2 * previous + 2 * next - 4 * current;
+ /* A flat peak (all three bins equal) would divide by zero and take
+ * fprintd down; it has no sub-bin offset to interpolate. */
+ int16_t interpolated = (int16_t) (
+ (denominator ? ((previous - next) * 0x200 - (denominator >> 1)) / denominator : 0) +
+ selected_bin * 0x200);
+ size_t pixel = (size_t) candidate->y * columns + (size_t) candidate->x;
+ int32_t neighborhood = feature_source[pixel] + feature_source[pixel - 1] +
+ feature_source[pixel + 1] +
+ feature_source[pixel - columns] +
+ feature_source[pixel + columns];
+ int32_t absolute_strength = candidate->strength;
+
+ if (interpolated < 0)
+ interpolated += 0x4800;
+ else if (interpolated >= 0x4800)
+ interpolated -= 0x4800;
+ int16_t feature_orientation =
+ (int16_t) ((((int32_t) interpolated * 0x6488) / 36) >> 9) - 0x3244;
+ if (feature_orientation < 0)
+ feature_orientation += 0x3244;
+ if (absolute_strength <= 0)
+ absolute_strength = -absolute_strength;
+
+ memset (record, 0, sizeof(*record));
+ record->foreground = neighborhood > 0x27f;
+ record->refined_x = candidate->refined_x;
+ record->refined_y = candidate->refined_y;
+ record->orientation = feature_orientation;
+ record->strength = -absolute_strength;
+ rank->strength = -absolute_strength;
+ rank->index = (int32_t) index;
+ *auxiliary = (GoodixMilanFeatureAux) {
+ candidate->x, candidate->y, candidate->scale_value, peak,
+ histogram[selected_bin], histogram[selected_bin] != peak, 0,
+ };
+}
+
+size_t
+goodix_milan_feature_collect_materialized (
+ const uint8_t *feature_source,
+ const uint16_t *scales,
+ const uint32_t *magnitude,
+ const int16_t *orientation,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureRecord *records,
+ GoodixMilanFeatureRank *ranks,
+ GoodixMilanFeatureAux *auxiliary,
+ size_t capacity)
+{
+ size_t cursor[3] = FEATURE_EXTREMA_CURSOR_INIT;
+ GoodixMilanFeatureExtremum extremum;
+ uint8_t *visited = calloc (rows * columns, 1);
+ size_t count = 0;
+
+ if (!visited)
+ return 0;
+ while (count < capacity &&
+ feature_next_extremum (scales, rows, columns, cursor, &extremum))
+ {
+ GoodixMilanFeatureCandidate candidate = {
+ extremum.x, extremum.y, extremum.scale, extremum.response,
+ 0, 0, 0,
+ };
+ uint32_t curvature = 0;
+
+ if (!goodix_milan_feature_refine_extremum (
+ scales, rows, columns, &candidate, &curvature))
+ continue;
+ size_t pixel = (size_t) candidate.y * columns + (size_t) candidate.x;
+ if (visited[pixel] != 0)
+ continue;
+ feature_materialize_candidate (
+ feature_source, magnitude, orientation, rows, columns, &candidate,
+ count, &records[count], &ranks[count], &auxiliary[count]);
+ visited[pixel] = 1;
+ count++;
+ }
+ free (visited);
+ return count;
+}
+
+static void
+feature_descriptor_sine_cosine (int16_t angle,
+ int32_t *sine,
+ int32_t *cosine)
+{
+ static const int16_t angles[13] = {
+ 0x0c91, 0x076b, 0x03eb, 0x01fd, 0x0100, 0x0080, 0x0040,
+ 0x0020, 0x0010, 0x0008, 0x0004, 0x0002, 0x0001,
+ };
+ int32_t reduced = angle;
+ int16_t sin_value = 0;
+ int16_t cos_value = 0x4000;
+ int16_t accumulated = 0;
+
+ if (reduced > 0x1922)
+ reduced = 0x3244 - reduced;
+ if (reduced == 0)
+ {
+ *sine = 0;
+ *cosine = angle > 0x1922 ? -0x4000 : 0x4000;
+ return;
+ }
+ if (reduced == 0x1922)
+ {
+ *sine = 0x4000;
+ *cosine = 0;
+ return;
+ }
+ for (size_t iteration = 0; iteration < 13; iteration++)
+ {
+ int16_t cos_shift = cos_value >> iteration;
+ int16_t sin_shift = sin_value >> iteration;
+ int16_t delta;
+
+ if (reduced - accumulated < 0)
+ {
+ cos_shift = (int16_t) -cos_shift;
+ delta = (int16_t) -angles[iteration];
+ }
+ else
+ {
+ sin_shift = (int16_t) -sin_shift;
+ delta = angles[iteration];
+ }
+ accumulated = (int16_t) (accumulated + delta);
+ sin_value = (int16_t) (sin_value + cos_shift);
+ cos_value = (int16_t) (cos_value + sin_shift);
+ }
+ *sine = ((int32_t) sin_value * 0x9b75 + 0x8000) >> 16;
+ *cosine = ((int32_t) cos_value * 0x9b75 + 0x8000) >> 16;
+ if (angle > 0x1922)
+ *cosine = -*cosine;
+}
+
+static void
+feature_descriptor_accumulate (uint32_t accumulator[6][6][8],
+ int32_t x,
+ int32_t y,
+ int32_t angle,
+ int32_t weight)
+{
+ int32_t x_bin = x >> 9;
+ int32_t y_bin = y >> 9;
+ int32_t x_fraction = x - x_bin * 0x200;
+ int32_t y_fraction = y - y_bin * 0x200;
+ int32_t orientation_bin = (angle >> 12) & 7;
+ int32_t next_orientation = (orientation_bin + 1) & 7;
+ int32_t orientation_fraction = angle - (angle >> 12) * 0x1000;
+ uint32_t scaled_weight = (uint32_t) (weight >> 9);
+ uint32_t upper_y = (uint32_t) (y_fraction * (int32_t) scaled_weight) >> 9;
+ uint32_t lower_y = scaled_weight - upper_y;
+ uint32_t upper_right =
+ (uint32_t) (x_fraction * (int32_t) upper_y) >> 9;
+ uint32_t lower_right =
+ (uint32_t) (x_fraction * (int32_t) lower_y) >> 9;
+ uint32_t cell_weight[2][2] = {
+ { lower_y - lower_right, lower_right },
+ { upper_y - upper_right, upper_right },
+ };
+
+ for (size_t cell_y = 0; cell_y < 2; cell_y++)
+ for (size_t cell_x = 0; cell_x < 2; cell_x++)
+ {
+ uint32_t value = cell_weight[cell_y][cell_x];
+ uint32_t orientation_part = value * orientation_fraction;
+ uint32_t *cell = accumulator[y_bin + 1 + (int32_t) cell_y]
+ [x_bin + 1 + (int32_t) cell_x];
+
+ cell[orientation_bin] +=
+ (value - (orientation_part >> 12)) >> 5;
+ cell[next_orientation] += orientation_part >> 17;
+ }
+}
+
+void
+goodix_milan_feature_build_descriptor_samples (
+ int32_t center_x,
+ int32_t center_y,
+ int32_t descriptor_scale,
+ int16_t feature_orientation,
+ const uint32_t *magnitude,
+ const int16_t *orientation,
+ size_t rows,
+ size_t columns,
+ int32_t samples[128])
+{
+ int32_t scale3 = descriptor_scale * 3;
+ int64_t radius_q16 = ((int64_t) scale3 * 0x38916) >> 16;
+ int32_t inverse_scale = (int32_t) (UINT64_C(0x1000000000) / scale3);
+ uint32_t weights[33 * 33] = { 0 };
+ uint32_t accumulator[6][6][8] = { 0 };
+ int32_t sine, cosine;
+ int32_t radius = (int32_t) ((radius_q16 >> 16) +
+ (((uint64_t) radius_q16 & 0x8000) != 0));
+
+ radius = radius > 32 ? 32 : radius;
+ size_t size = (size_t) radius + 1;
+ uint32_t coefficient =
+ (uint32_t) (UINT64_C(0x200000000000) /
+ ((int64_t) scale3 * scale3));
+ feature_build_orientation_weights (weights, size, coefficient);
+ feature_descriptor_sine_cosine (feature_orientation, &sine, &cosine);
+ cosine = (int32_t) (((int64_t) cosine * inverse_scale) >> 25);
+ sine = (int32_t) (((int64_t) sine * inverse_scale) >> 25);
+ int32_t min_y = 1 - center_y > -radius ? 1 - center_y : -radius;
+ int32_t max_y = (int32_t) rows - center_y - 2 < radius
+ ? (int32_t) rows - center_y - 2
+ : radius;
+ int32_t min_x = 1 - center_x > -radius ? 1 - center_x : -radius;
+ int32_t max_x = (int32_t) columns - center_x - 2 < radius
+ ? (int32_t) columns - center_x - 2
+ : radius;
+
+ for (int32_t delta_y = min_y; delta_y <= max_y; delta_y++)
+ for (int32_t delta_x = min_x; delta_x <= max_x; delta_x++)
+ {
+ int32_t rotated_x = delta_x * cosine - delta_y * sine;
+ int32_t rotated_y = delta_x * sine + delta_y * cosine;
+ size_t pixel = (size_t) (center_y + delta_y) * columns +
+ (size_t) (center_x + delta_x);
+
+ if (abs (rotated_x) >= 0x500 || abs (rotated_y) >= 0x500)
+ continue;
+ int32_t relative = 0x3244 - orientation[pixel] -
+ feature_orientation;
+ relative %= 0x6488;
+ if (relative < 0)
+ relative += 0x6488;
+ int32_t angle = (int32_t) (((uint32_t) relative * 0x145f3U) >> 16);
+ int32_t weighted = (int32_t) (
+ magnitude[pixel] *
+ weights[(size_t) abs (delta_y) * size + (size_t) abs (delta_x)]);
+ feature_descriptor_accumulate (accumulator, rotated_x + 0x300,
+ rotated_y + 0x300, angle, weighted);
+ }
+ for (size_t y = 0; y < 4; y++)
+ for (size_t x = 0; x < 4; x++)
+ for (size_t bin = 0; bin < 8; bin++)
+ samples[(y * 4 + x) * 8 + bin] = accumulator[y + 1][x + 1][bin];
+}
+
+static uint64_t
+feature_integer_square_root (uint64_t value)
+{
+ uint64_t result = 0;
+ uint64_t bit = UINT64_C(1) << 62;
+
+ while (bit > value)
+ bit >>= 2;
+ while (bit != 0)
+ {
+ if (value >= result + bit)
+ {
+ value -= result + bit;
+ result = (result >> 1) + bit;
+ }
+ else
+ result >>= 1;
+ bit >>= 2;
+ }
+ return result;
+}
+
+static void
+feature_normalize_descriptor (const int32_t *samples,
+ size_t count,
+ int16_t *normalized)
+{
+ uint64_t energy = 0;
+
+ for (size_t i = 0; i < count; i++)
+ energy += (uint64_t) (uint32_t) samples[i] * (uint32_t) samples[i];
+ uint32_t threshold =
+ (uint32_t) ((feature_integer_square_root (energy) * 0x3333) >> 16);
+ int16_t clipped = (int16_t) feature_integer_square_root (threshold);
+ for (size_t i = 0; i < count; i++)
+ normalized[i] = (int16_t) (
+ samples[i] < (int32_t) threshold
+ ? (int16_t) feature_integer_square_root ((uint32_t) samples[i])
+ : (int16_t) clipped);
+}
+
+static void
+feature_hadamard32 (const int16_t *normalized,
+ int32_t transformed[32])
+{
+ for (size_t i = 0; i < 32; i++)
+ transformed[i] = normalized[i];
+ for (size_t stride = 1; stride < 32; stride *= 2)
+ for (size_t base = 0; base < 32; base += stride * 2)
+ for (size_t i = 0; i < stride; i++)
+ {
+ int32_t a = transformed[base + i];
+ int32_t b = transformed[base + i + stride];
+
+ transformed[base + i] = a + b;
+ transformed[base + i + stride] = a - b;
+ }
+}
+
+static int16_t
+feature_descriptor_median (const int16_t *values,
+ size_t count)
+{
+ int16_t sorted[128];
+
+ memcpy (sorted, values, count * sizeof(*values));
+ for (size_t i = 1; i < count; i++)
+ {
+ int16_t value = sorted[i];
+ size_t position = i;
+
+ while (position > 0 && value < sorted[position - 1])
+ {
+ sorted[position] = sorted[position - 1];
+ position--;
+ }
+ sorted[position] = value;
+ }
+ return sorted[(count - 1) / 2];
+}
+
+static void
+feature_encode_descriptor_first (const int16_t normalized[128],
+ uint8_t *record)
+{
+ static const int coefficients[4][4] = {
+ { 1, 1, 1, 1 }, { 1, -1, 1, -1 },
+ { 1, 1, -1, -1 }, { 1, -1, -1, 1 },
+ };
+ uint32_t transform[4] = { 0 };
+ uint32_t median_bits = 0;
+ int16_t partial[4][32];
+
+ for (size_t block = 0; block < 4; block++)
+ {
+ int32_t transformed[32];
+
+ feature_hadamard32 (normalized + block * 32, transformed);
+ /* Narrow each block before the existing four-block combination. */
+ for (size_t bit = 0; bit < 32; bit++)
+ partial[block][bit] = (int16_t) transformed[bit];
+ }
+
+ for (size_t bit = 0; bit < 32; bit++)
+ {
+ for (size_t output = 0; output < 4; output++)
+ {
+ int32_t sum = 0;
+ for (size_t block = 0; block < 4; block++)
+ sum += coefficients[output][block] * partial[block][bit];
+ if (sum > 0)
+ transform[output] |= 1U << bit;
+ }
+ }
+ int16_t median = feature_descriptor_median (normalized, 128);
+ for (size_t bit = 0; bit < 32; bit++)
+ if (median < normalized[bit * 4 + 1])
+ median_bits |= 1U << bit;
+ memset (record + 0x10, 0, 0x18);
+ memcpy (record + 0x10, transform, sizeof(transform));
+ memcpy (record + 0x20, &median_bits, sizeof(median_bits));
+}
+
+static void
+feature_encode_descriptor_second (const int16_t normalized[32],
+ uint8_t *record)
+{
+ uint32_t transform = 0;
+ uint32_t median_bits = 0;
+ int16_t median = feature_descriptor_median (normalized, 32);
+ int32_t transformed[32];
+
+ feature_hadamard32 (normalized, transformed);
+
+ for (size_t bit = 0; bit < 32; bit++)
+ {
+ if (transformed[bit] > 0)
+ transform |= 1U << bit;
+ if (median < normalized[bit])
+ median_bits |= 1U << bit;
+ }
+ memset (record + 0x28, 0, 0x10);
+ memcpy (record + 0x28, &transform, sizeof(transform));
+ memcpy (record + 0x2c, &median_bits, sizeof(median_bits));
+}
+
+void
+feature_build_descriptor (const uint32_t *magnitude,
+ const int16_t *orientation,
+ size_t rows,
+ size_t columns,
+ int32_t descriptor_scale,
+ const GoodixMilanFeatureAux *auxiliary,
+ GoodixMilanFeatureRecord *record)
+{
+ int32_t samples[128];
+ int32_t central[32];
+ int16_t normalized[128];
+ int16_t central_normalized[32];
+
+ goodix_milan_feature_build_descriptor_samples (
+ auxiliary->x, auxiliary->y, descriptor_scale,
+ record->orientation, magnitude, orientation, rows, columns, samples);
+ feature_normalize_descriptor (samples, 128, normalized);
+ feature_encode_descriptor_first (normalized, (uint8_t *) record);
+ memcpy (central, samples + 40, 8 * sizeof(*central));
+ memcpy (central + 8, samples + 48, 8 * sizeof(*central));
+ memcpy (central + 16, samples + 72, 8 * sizeof(*central));
+ memcpy (central + 24, samples + 80, 8 * sizeof(*central));
+ feature_normalize_descriptor (central, 32, central_normalized);
+ feature_encode_descriptor_second (central_normalized, (uint8_t *) record);
+}
+
+static int
+feature_rank_compare (const void *left,
+ const void *right)
+{
+ const GoodixMilanFeatureRank *a = left;
+ const GoodixMilanFeatureRank *b = right;
+
+ if (a->strength != b->strength)
+ return a->strength < b->strength ? -1 : 1;
+ return (a->index > b->index) - (a->index < b->index);
+}
+
+size_t
+feature_finish_pretransform_records (
+ const uint32_t *magnitude,
+ const int16_t *orientation,
+ size_t rows,
+ size_t columns,
+ GoodixMilanFeatureRecord *records,
+ size_t capacity,
+ GoodixMilanFeatureRecord *materialized,
+ GoodixMilanFeatureRank *ranks,
+ const GoodixMilanFeatureAux *auxiliary,
+ size_t count)
+{
+ size_t output_count = count < capacity ? count : capacity;
+
+ if (count > capacity)
+ qsort (ranks, count, sizeof(*ranks), feature_rank_compare);
+ for (size_t i = 0; i < output_count; i++)
+ {
+ size_t index = count > capacity ? (size_t) ranks[i].index : i;
+ records[i] = materialized[index];
+ feature_build_descriptor (magnitude, orientation, rows, columns, 0x1adfe,
+ &auxiliary[index], &records[i]);
+ int32_t boundary;
+ if ((uint16_t) records[i].refined_y < 0x1400)
+ boundary = 1;
+ else if ((uint16_t) records[i].refined_y >=
+ (uint16_t) (rows * 0x100 - 0x1400))
+ boundary = 2;
+ else
+ boundary = 0;
+ memcpy (records[i].payload, &boundary, sizeof(boundary));
+ records[i].refined_x =
+ (int16_t) (((uint16_t) records[i].refined_x + 8) & 0xfff0);
+ records[i].refined_y =
+ (int16_t) (((uint16_t) records[i].refined_y + 8) & 0xfff0);
+ if (records[i].orientation < 0)
+ records[i].orientation = (int16_t) -(
+ (0x80 - (int32_t) records[i].orientation) & 0xff00);
+ else
+ records[i].orientation = (int16_t) (
+ ((int32_t) records[i].orientation + 0x80) & 0xff00);
+ }
+ return output_count;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/feature/record.c b/libfprint/drivers/goodix53x5/milan/feature/record.c
new file mode 100644
index 0000000..a2bbb69
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/feature/record.c
@@ -0,0 +1,120 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan feature records
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/feature/feature.h"
+
+#include <string.h>
+
+/* In-place 56-byte descriptor transform recovered from FUN_180047ae0. */
+enum {
+ MILAN_FEATURE_RECORD_SIZE = 56,
+ MILAN_FEATURE_PAIR_COUNT = 8,
+ MILAN_FEATURE_PAIR_OFFSET = 16,
+ MILAN_FEATURE_SOURCE_WORD_OFFSET = 32,
+ MILAN_FEATURE_REVERSED_WORD_OFFSET = 36,
+ MILAN_FEATURE_TAIL_OFFSET = 40,
+ MILAN_FEATURE_EXPANDED_TAIL_OFFSET = 48,
+ MILAN_FEATURE_PARTITION_MASK = 3,
+ MILAN_FEATURE_LEFT_CLASS = 0,
+ MILAN_FEATURE_RIGHT_CLASS = 1,
+};
+
+static void
+milan_feature_expand_record (uint8_t *record)
+{
+ uint32_t bits;
+ uint32_t reversed = 0;
+
+ memcpy (&bits, record + MILAN_FEATURE_SOURCE_WORD_OFFSET, sizeof (bits));
+ for (size_t i = 0; i < 32; i++)
+ reversed |= ((bits >> i) & 1U) << (31 - i);
+ memcpy (record + MILAN_FEATURE_REVERSED_WORD_OFFSET,
+ &reversed, sizeof (reversed));
+ record[MILAN_FEATURE_EXPANDED_TAIL_OFFSET] =
+ record[MILAN_FEATURE_TAIL_OFFSET];
+ record[MILAN_FEATURE_EXPANDED_TAIL_OFFSET + 1] =
+ (uint8_t) ~record[MILAN_FEATURE_TAIL_OFFSET + 1];
+ record[MILAN_FEATURE_EXPANDED_TAIL_OFFSET + 2] =
+ (uint8_t) ~record[MILAN_FEATURE_TAIL_OFFSET + 2];
+ record[MILAN_FEATURE_EXPANDED_TAIL_OFFSET + 3] =
+ record[MILAN_FEATURE_TAIL_OFFSET + 3];
+ for (size_t i = 0; i < 4; i++)
+ record[MILAN_FEATURE_EXPANDED_TAIL_OFFSET + 4 + i] =
+ record[MILAN_FEATURE_TAIL_OFFSET + 7 - i];
+}
+
+void
+goodix_milan_feature_transform_record (uint8_t *record,
+ int reverse_bits)
+{
+ static const uint8_t swap_order[MILAN_FEATURE_PAIR_COUNT] = {
+ 0, 1, 1, 0, 1, 0, 0, 1,
+ };
+ uint8_t first[MILAN_FEATURE_PAIR_COUNT];
+ uint8_t second[MILAN_FEATURE_PAIR_COUNT];
+
+ for (size_t i = 0; i < MILAN_FEATURE_PAIR_COUNT; i++)
+ {
+ uint8_t left = record[MILAN_FEATURE_PAIR_OFFSET + i * 2];
+ uint8_t right = record[MILAN_FEATURE_PAIR_OFFSET + i * 2 + 1];
+ uint8_t high_left = ((left ^ right) & 0x0f) ^ left;
+ uint8_t high_right = ((left ^ right) & 0x0f) ^ right;
+
+ first[i] = swap_order[i] == 0 ? high_right : high_left;
+ second[i] = swap_order[i] == 0 ? high_left : high_right;
+ }
+ memcpy (record + MILAN_FEATURE_PAIR_OFFSET, first, sizeof (first));
+ memcpy (record + MILAN_FEATURE_PAIR_OFFSET + MILAN_FEATURE_PAIR_COUNT,
+ second, sizeof (second));
+ memset (record + MILAN_FEATURE_REVERSED_WORD_OFFSET, 0, sizeof (uint32_t));
+
+ if (reverse_bits)
+ milan_feature_expand_record (record);
+}
+
+/* Partition Boolean low classes in place. End swaps make this deliberately
+ * unstable; low classes 2/3 are outside the producer contract. */
+size_t
+goodix_milan_feature_partition_records (uint8_t *records,
+ size_t record_count)
+{
+ size_t left = 0;
+ size_t right;
+
+ if (record_count == 0)
+ return 0;
+ right = record_count - 1;
+ while (left < right)
+ {
+ while (left < right &&
+ (records[left * MILAN_FEATURE_RECORD_SIZE] &
+ MILAN_FEATURE_PARTITION_MASK) == MILAN_FEATURE_LEFT_CLASS)
+ left++;
+ while (left < right &&
+ (records[right * MILAN_FEATURE_RECORD_SIZE] &
+ MILAN_FEATURE_PARTITION_MASK) == MILAN_FEATURE_RIGHT_CLASS)
+ right--;
+ if (left < right)
+ {
+ uint8_t temporary[MILAN_FEATURE_RECORD_SIZE];
+
+ memcpy (temporary, records + left * MILAN_FEATURE_RECORD_SIZE,
+ sizeof (temporary));
+ memcpy (records + left * MILAN_FEATURE_RECORD_SIZE,
+ records + right * MILAN_FEATURE_RECORD_SIZE,
+ sizeof (temporary));
+ memcpy (records + right * MILAN_FEATURE_RECORD_SIZE,
+ temporary, sizeof (temporary));
+ }
+ }
+ return left +
+ ((records[left * MILAN_FEATURE_RECORD_SIZE] &
+ MILAN_FEATURE_PARTITION_MASK) == MILAN_FEATURE_LEFT_CLASS);
+}
diff --git a/libfprint/drivers/goodix53x5/milan/match/admission.c b/libfprint/drivers/goodix53x5/milan/match/admission.c
new file mode 100644
index 0000000..babe433
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/admission.c
@@ -0,0 +1,269 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan match admission predicates
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/milan.h"
+#include "milan/print.h"
+
+#include <string.h>
+
+enum {
+ AFFINE_XX,
+ AFFINE_XY,
+ AFFINE_X_OFFSET,
+ AFFINE_YX,
+ AFFINE_YY,
+ AFFINE_Y_OFFSET,
+ AFFINE_WORDS,
+};
+
+#define AFFINE_Q8_ONE 0x100
+#define PROXIMITY_PRIMARY_SENSOR_MASK UINT32_C (0x472010)
+#define PROXIMITY_ALTERNATE_SENSOR_MASK UINT64_C (0xc000000000001ec5)
+
+enum {
+ METRIC_PRIMARY_COUNT = 0,
+ METRIC_FILTERED_COUNT = 1,
+ METRIC_OVERLAP_SCORE = 4,
+ METRIC_DETAIL = 5,
+ METRIC_COVERAGE = 9,
+ METRIC_TOPOLOGY = 10,
+ METRIC_GEOMETRY = 11,
+ METRIC_SCALE_PENALTY = 12,
+ METRIC_ORTHOGONALITY_PENALTY = 13,
+};
+
+enum {
+ CONFIG_DETAIL_BASELINE = 0,
+ CONFIG_COUNT_SHIFT = 1,
+ CONFIG_SENSOR_TYPE = 15,
+ CONFIG_AFFINE_PENALTY = 16,
+};
+
+#define ADMISSION_THRESHOLD_FAMILY_SIZE 8
+#define ADMISSION_FILTERED_FAMILY 0
+#define ADMISSION_PRIMARY_FAMILY ADMISSION_THRESHOLD_FAMILY_SIZE
+#define ADMISSION_FILTERED_CONFIG_FAMILY (2 * ADMISSION_THRESHOLD_FAMILY_SIZE)
+#define ADMISSION_COUNT_BAND_BASE 7
+#define ADMISSION_COUNT_BAND_MAX 7
+#define ADMISSION_TOPOLOGY_BASELINE 60
+#define ADMISSION_TOPOLOGY_STEP 5
+#define ADMISSION_COVERAGE_BASELINE 128
+#define ADMISSION_COVERAGE_STEP 10
+#define ADMISSION_AFFINE_PENALTY_SCALE 4
+
+static int32_t
+admission_count_band (int32_t count)
+{
+ int32_t index = count - ADMISSION_COUNT_BAND_BASE;
+
+ if (index < 0)
+ return 0;
+ if (index > ADMISSION_COUNT_BAND_MAX)
+ return ADMISSION_COUNT_BAND_MAX;
+ return index;
+}
+
+int
+goodix_milan_match_fallback_candidate_eligible (
+ int32_t composite_score,
+ int32_t score_threshold,
+ int32_t quality_metric)
+{
+ return composite_score > score_threshold && quality_metric > 195;
+}
+
+int
+goodix_milan_match_transform_proximity (const int32_t transform[6],
+ int32_t mode,
+ uint32_t sensor_type)
+{
+ static const int32_t identity[AFFINE_WORDS] = {
+ [AFFINE_XX] = AFFINE_Q8_ONE,
+ [AFFINE_YY] = AFFINE_Q8_ONE,
+ };
+ static const int32_t default_limits[AFFINE_WORDS] = {
+ 15, 11, 0x400, 11, 15, 0x400,
+ };
+ static const int32_t mode4_limits[AFFINE_WORDS] = {
+ 38, 38, 0xc00, 38, 38, 0xc00,
+ };
+ static const int32_t mode5_limits[AFFINE_WORDS] = {
+ 45, 40, 0xf00, 40, 45, 0xf00,
+ };
+ static const int32_t alternate_sensor_limits[AFFINE_WORDS] = {
+ 25, 21, 0x700, 21, 25, 0x700,
+ };
+ int32_t limits[AFFINE_WORDS];
+ int32_t multiplier = 1;
+
+ if (mode < 1 || mode > 5)
+ return 0;
+ memcpy (limits, default_limits, sizeof (limits));
+ if (mode == 3)
+ multiplier = 2;
+ else if (mode == 4)
+ memcpy (limits, mode4_limits, sizeof (limits));
+ else if (mode == 5)
+ memcpy (limits, mode5_limits, sizeof (limits));
+ if (sensor_type < 23 &&
+ ((PROXIMITY_PRIMARY_SENSOR_MASK >> sensor_type) & 1) != 0)
+ {
+ if (mode == 2)
+ multiplier = 2;
+ }
+ else
+ {
+ if (sensor_type >= 64 ||
+ ((PROXIMITY_ALTERNATE_SENSOR_MASK >> sensor_type) & 1) == 0)
+ return 0;
+ /* Preserve current mode-1 limits for alternate-family modes 4/5. Native
+ * uses their wider tables, but profile-9/type-12 cannot reach them. */
+ memcpy (limits, alternate_sensor_limits, sizeof (limits));
+ multiplier = 1;
+ }
+ for (size_t i = 0; i < AFFINE_WORDS; i++)
+ {
+ int32_t delta = transform[i] - identity[i];
+
+ if ((delta < 0 ? -delta : delta) > limits[i] * multiplier)
+ return 0;
+ }
+ return 1;
+}
+
+int
+goodix_milan_match_initial_flags (
+ const int32_t metrics[77],
+ int32_t image_quality,
+ int32_t image_coverage,
+ const int32_t configuration[19],
+ int32_t *match_flag,
+ int32_t *candidate_flag,
+ int32_t *optional_flag)
+{
+ static const int32_t thresholds[24] = {
+ 0x0fffffff, 0x0fffffff, 0xd1, 0xd0, 0xd0, 0xcf, 0xcf, 0xcf,
+ 0x0fffffff, 0xce, 0xc9, 0xc4, 0xb9, 0xb9, 0xb9, 0xb9,
+ 0x0fffffff, 0x0fffffff, 0x0fffffff, 0xcf, 0xcd, 0xcb, 0xc4, 0xbb,
+ };
+ int32_t policy_thresholds[24];
+ int32_t primary_count;
+ int32_t filtered_count;
+ int32_t detail;
+ int32_t coverage;
+ int32_t topology;
+ int32_t detail_delta;
+ int32_t adjusted_detail;
+ int32_t filtered_index;
+ int32_t primary_threshold_index;
+ int32_t adjustment = 0;
+
+ if (!metrics || !configuration || !match_flag || !candidate_flag)
+ return -1;
+ memcpy (policy_thresholds, thresholds, sizeof (policy_thresholds));
+ if (configuration[CONFIG_SENSOR_TYPE] == GOODIX_MILAN_PRINT_SENSOR_TYPE)
+ {
+ policy_thresholds[2] = 0xdc;
+ policy_thresholds[3] = 0xd8;
+ policy_thresholds[4] = 0xd7;
+ policy_thresholds[5] = 0xd4;
+ policy_thresholds[6] = 0xd3;
+ policy_thresholds[7] = 0xd2;
+ }
+
+ primary_count = metrics[METRIC_PRIMARY_COUNT];
+ filtered_count = metrics[METRIC_FILTERED_COUNT];
+ detail = metrics[METRIC_DETAIL];
+ coverage = metrics[METRIC_COVERAGE];
+ topology = metrics[METRIC_TOPOLOGY];
+ detail_delta = detail - configuration[CONFIG_DETAIL_BASELINE];
+ adjusted_detail = detail - (primary_count < 5 ? 4 : 0);
+ if (topology > ADMISSION_TOPOLOGY_BASELINE && primary_count > 4)
+ {
+ adjustment = 1 + (topology - ADMISSION_TOPOLOGY_BASELINE) /
+ ADMISSION_TOPOLOGY_STEP;
+ primary_count += adjustment;
+ filtered_count += adjustment;
+ }
+ if (coverage < ADMISSION_COVERAGE_BASELINE)
+ {
+ adjustment = 1 + (ADMISSION_COVERAGE_BASELINE - coverage) /
+ ADMISSION_COVERAGE_STEP;
+ primary_count -= adjustment;
+ filtered_count -= adjustment;
+ }
+
+ filtered_index = admission_count_band (filtered_count);
+ primary_threshold_index = admission_count_band (
+ primary_count - configuration[CONFIG_COUNT_SHIFT]);
+ int32_t filtered_threshold_index = admission_count_band (
+ filtered_count - configuration[CONFIG_COUNT_SHIFT]);
+
+ if (configuration[CONFIG_AFFINE_PENALTY] != 0 && filtered_count < 11)
+ {
+ int32_t penalty =
+ (metrics[METRIC_SCALE_PENALTY] +
+ metrics[METRIC_ORTHOGONALITY_PENALTY]) *
+ ADMISSION_AFFINE_PENALTY_SCALE;
+
+ detail_delta -= penalty;
+ adjusted_detail -= penalty;
+ }
+ *candidate_flag = 1;
+ if (detail_delta <=
+ policy_thresholds[primary_threshold_index + ADMISSION_PRIMARY_FAMILY] &&
+ detail_delta <=
+ policy_thresholds[filtered_threshold_index +
+ ADMISSION_FILTERED_CONFIG_FAMILY] &&
+ primary_count < 14)
+ *candidate_flag = 0;
+
+ if (configuration[CONFIG_SENSOR_TYPE] == 7)
+ {
+ int32_t first_adjust = filtered_count > primary_count && primary_count <= 7 &&
+ metrics[METRIC_ORTHOGONALITY_PENALTY] != 0;
+ int32_t second_adjust = coverage <= 100 && filtered_count <= 11 &&
+ topology <= 65;
+
+ adjusted_detail -= (first_adjust * 3 + second_adjust) * 2;
+ }
+ if (*candidate_flag == 0 || image_quality < 16 || image_coverage < 65 ||
+ ((primary_count < 5 && metrics[METRIC_OVERLAP_SCORE] < 235 &&
+ adjusted_detail < 217)) ||
+ (((adjusted_detail <=
+ policy_thresholds[filtered_index + ADMISSION_FILTERED_FAMILY] &&
+ (adjusted_detail < 195 || primary_count < 16) &&
+ (adjusted_detail < 190 || primary_count < 18) &&
+ (filtered_count < 19 || primary_count < 11 || adjusted_detail < 197) &&
+ (topology < 61 || detail_delta < 198 || primary_count < 13) &&
+ (filtered_count < 17 || primary_count < 11 || detail_delta < 201)))))
+ *match_flag = 0;
+ else
+ *match_flag = 1;
+
+ if (optional_flag)
+ {
+ if ((primary_count < 21 || detail_delta < 185) && detail_delta < 205 &&
+ detail_delta <
+ policy_thresholds[primary_threshold_index +
+ ADMISSION_PRIMARY_FAMILY] + 10 &&
+ detail_delta <
+ policy_thresholds[filtered_threshold_index +
+ ADMISSION_FILTERED_CONFIG_FAMILY] + 10)
+ *optional_flag = 1;
+ else
+ *optional_flag = 0;
+ }
+ if (*match_flag == 1 && metrics[METRIC_PRIMARY_COUNT] >= 8 &&
+ metrics[METRIC_FILTERED_COUNT] >= 12 &&
+ metrics[METRIC_GEOMETRY] >= 36)
+ (*match_flag)++;
+ return 0;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/match/candidate.c b/libfprint/drivers/goodix53x5/milan/match/candidate.c
new file mode 100644
index 0000000..c416e88
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/candidate.c
@@ -0,0 +1,143 @@
+/*
+ * Goodix 53x5 driver for libfprint - profile-9/type-12 candidate state
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This is the candidate construction boundary immediately before profile-9/
+ * subtype-12 policy evaluation. It keeps the 77-word metrics layout in one
+ * place instead of reconstructing selected fields throughout the matcher.
+ */
+
+#include "milan/match/candidate.h"
+
+#include <string.h>
+
+void
+goodix_milan_match_candidate_reset (GoodixMilanMatchCandidate *candidate)
+{
+ memset (candidate, 0, sizeof(*candidate));
+}
+
+void
+goodix_milan_match_candidate_set_primary (GoodixMilanMatchCandidate *candidate,
+ int32_t primary_count,
+ int32_t retained_count,
+ const int32_t transform[6])
+{
+ candidate->words[GOODIX_MILAN_CANDIDATE_PRIMARY_COUNT] = primary_count;
+ candidate->words[GOODIX_MILAN_CANDIDATE_RETAINED_COUNT] = retained_count;
+ memcpy (candidate->transform, transform, sizeof(candidate->transform));
+}
+
+int
+goodix_milan_match_candidate_rank_alternate (
+ int32_t primary_detail,
+ int32_t primary_scale_penalty,
+ int32_t primary_orthogonality_penalty,
+ int32_t alternate_score,
+ int32_t alternate_detail,
+ int32_t alternate_scale_penalty,
+ int32_t alternate_orthogonality_penalty)
+{
+ return alternate_score > 128 &&
+ alternate_detail -
+ 4 * (alternate_scale_penalty +
+ alternate_orthogonality_penalty) >
+ primary_detail -
+ 4 * (primary_scale_penalty + primary_orthogonality_penalty);
+}
+
+int
+goodix_milan_match_candidate_promote_alternate (int32_t mask_overlap,
+ int32_t topology_percent,
+ int32_t geometric_percent,
+ int32_t alternate_count)
+{
+ return (mask_overlap >= 145 && topology_percent >= 40) ||
+ (mask_overlap < 105 && topology_percent > 65 &&
+ geometric_percent > 50) ||
+ (mask_overlap >= 105 && topology_percent >= 45 &&
+ geometric_percent > 25) ||
+ geometric_percent > 80 || alternate_count > 18;
+}
+
+void
+goodix_milan_match_candidate_set_record_metrics (
+ GoodixMilanMatchCandidate *candidate,
+ int32_t valid_count,
+ int32_t matched_count,
+ int32_t topology_percent,
+ int32_t geometric_percent,
+ int32_t topology_distance)
+{
+ candidate->words[GOODIX_MILAN_CANDIDATE_TOPOLOGY_PERCENT] = topology_percent;
+ candidate->words[GOODIX_MILAN_CANDIDATE_GEOMETRIC_PERCENT] = geometric_percent;
+ candidate->words[GOODIX_MILAN_CANDIDATE_VALID_RECORD_COUNT] = valid_count;
+ candidate->words[GOODIX_MILAN_CANDIDATE_MATCHED_RECORD_COUNT] = matched_count;
+ candidate->words[GOODIX_MILAN_CANDIDATE_RECORD_TOPOLOGY_PERCENT] =
+ topology_percent;
+ candidate->words[GOODIX_MILAN_CANDIDATE_RECORD_GEOMETRIC_PERCENT] =
+ geometric_percent;
+ candidate->words[GOODIX_MILAN_CANDIDATE_TOPOLOGY_DISTANCE] = topology_distance;
+}
+
+void
+goodix_milan_match_candidate_set_sibling (
+ GoodixMilanMatchCandidate *candidate,
+ int32_t sibling_count,
+ const int32_t sibling_transform[6],
+ int32_t valid_count,
+ int32_t matched_count,
+ int32_t topology_percent,
+ int32_t geometric_percent,
+ int32_t topology_distance,
+ int select_transform)
+{
+ candidate->words[GOODIX_MILAN_CANDIDATE_SIBLING_COUNT] = sibling_count;
+ if (select_transform)
+ memcpy (candidate->transform, sibling_transform,
+ sizeof(candidate->transform));
+ goodix_milan_match_candidate_set_record_metrics (
+ candidate, valid_count, matched_count, topology_percent,
+ geometric_percent, topology_distance);
+}
+
+int
+goodix_milan_match_candidate_skip_pre_primary (
+ int32_t configured_feature_mode,
+ int32_t configured_feature_index,
+ size_t feature_index,
+ size_t feature_count,
+ int32_t maximum_features,
+ int32_t rejection_gate,
+ int32_t retained_feature_flag,
+ int32_t feature_active)
+{
+ if (configured_feature_mode == 0 &&
+ feature_index != (size_t) configured_feature_index)
+ return 1;
+
+ return (feature_count == (size_t) maximum_features ||
+ rejection_gate == 1) &&
+ retained_feature_flag == 1 && feature_active == 1;
+}
+
+int
+goodix_milan_match_candidate_admit (GoodixMilanMatchCandidate *candidate)
+{
+ if (candidate->words[GOODIX_MILAN_CANDIDATE_SIBLING_COUNT] >
+ candidate->words[GOODIX_MILAN_CANDIDATE_RETAINED_COUNT])
+ candidate->words[GOODIX_MILAN_CANDIDATE_RETAINED_COUNT] =
+ candidate->words[GOODIX_MILAN_CANDIDATE_SIBLING_COUNT];
+
+ return candidate->words[GOODIX_MILAN_CANDIDATE_RETAINED_COUNT] > 4 &&
+ candidate->words[GOODIX_MILAN_CANDIDATE_TOPOLOGY_PERCENT] >= 30;
+}
+
+void
+goodix_milan_match_candidate_materialize_dispatch (
+ GoodixMilanMatchCandidate *candidate)
+{
+ memcpy (candidate->words + GOODIX_MILAN_CANDIDATE_TRANSFORM_FIRST,
+ candidate->transform,
+ sizeof(candidate->transform));
+}
diff --git a/libfprint/drivers/goodix53x5/milan/match/candidate.h b/libfprint/drivers/goodix53x5/milan/match/candidate.h
new file mode 100644
index 0000000..5c17a53
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/candidate.h
@@ -0,0 +1,105 @@
+/*
+ * Goodix 53x5 driver for libfprint - profile-9/type-12 candidate state
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include <stddef.h>
+#include <stdint.h>
+
+#define GOODIX_MILAN_CANDIDATE_WORDS 77
+
+typedef enum
+{
+ GOODIX_MILAN_CANDIDATE_PRIMARY_COUNT = 0,
+ GOODIX_MILAN_CANDIDATE_RETAINED_COUNT = 1,
+ GOODIX_MILAN_CANDIDATE_SIBLING_COUNT = 2,
+ GOODIX_MILAN_CANDIDATE_OVERLAP_SCORE = 4,
+ GOODIX_MILAN_CANDIDATE_OVERLAP_DETAIL = 5,
+ GOODIX_MILAN_CANDIDATE_LOW_DETAIL = 8,
+ GOODIX_MILAN_CANDIDATE_OVERLAP_COVERAGE_Q8 = 9,
+ GOODIX_MILAN_CANDIDATE_TOPOLOGY_PERCENT = 10,
+ GOODIX_MILAN_CANDIDATE_GEOMETRIC_PERCENT = 11,
+ GOODIX_MILAN_CANDIDATE_SCALE_PENALTY = 12,
+ GOODIX_MILAN_CANDIDATE_ORTHOGONALITY_PENALTY = 13,
+ GOODIX_MILAN_CANDIDATE_STRONG_ORTHOGONALITY_PENALTY = 14,
+ GOODIX_MILAN_CANDIDATE_TRANSFORM_FIRST = 15,
+ GOODIX_MILAN_CANDIDATE_TRANSFORM_LAST = 20,
+ GOODIX_MILAN_CANDIDATE_VALID_RECORD_COUNT = 66,
+ GOODIX_MILAN_CANDIDATE_MATCHED_RECORD_COUNT = 67,
+ GOODIX_MILAN_CANDIDATE_RECORD_TOPOLOGY_PERCENT = 68,
+ GOODIX_MILAN_CANDIDATE_RECORD_GEOMETRIC_PERCENT = 69,
+ GOODIX_MILAN_CANDIDATE_TOPOLOGY_DISTANCE = 70,
+} GoodixMilanCandidateWord;
+
+typedef struct
+{
+ int32_t words[GOODIX_MILAN_CANDIDATE_WORDS];
+ int32_t transform[6];
+ /* Native validity is private and does not consume recovered candidate words. */
+ int primary_valid;
+ int alternate_valid;
+} GoodixMilanMatchCandidate;
+
+void goodix_milan_match_candidate_reset (GoodixMilanMatchCandidate *candidate);
+
+void goodix_milan_match_candidate_set_primary (
+ GoodixMilanMatchCandidate *candidate,
+ int32_t primary_count,
+ int32_t retained_count,
+ const int32_t transform[6]);
+
+int goodix_milan_match_candidate_rank_alternate (
+ int32_t primary_detail,
+ int32_t primary_scale_penalty,
+ int32_t primary_orthogonality_penalty,
+ int32_t alternate_score,
+ int32_t alternate_detail,
+ int32_t alternate_scale_penalty,
+ int32_t alternate_orthogonality_penalty);
+
+int goodix_milan_match_candidate_promote_alternate (
+ int32_t mask_overlap,
+ int32_t topology_percent,
+ int32_t geometric_percent,
+ int32_t alternate_count);
+
+void goodix_milan_match_candidate_set_record_metrics (
+ GoodixMilanMatchCandidate *candidate,
+ int32_t valid_count,
+ int32_t matched_count,
+ int32_t topology_percent,
+ int32_t geometric_percent,
+ int32_t topology_distance);
+
+void goodix_milan_match_candidate_set_sibling (
+ GoodixMilanMatchCandidate *candidate,
+ int32_t sibling_count,
+ const int32_t sibling_transform[6],
+ int32_t valid_count,
+ int32_t matched_count,
+ int32_t topology_percent,
+ int32_t geometric_percent,
+ int32_t topology_distance,
+ int select_transform);
+
+int goodix_milan_match_candidate_skip_pre_primary (
+ int32_t configured_feature_mode,
+ int32_t configured_feature_index,
+ size_t feature_index,
+ size_t feature_count,
+ int32_t maximum_features,
+ int32_t rejection_gate,
+ int32_t retained_feature_flag,
+ int32_t feature_active);
+
+int goodix_milan_match_candidate_admit (GoodixMilanMatchCandidate *candidate);
+
+void goodix_milan_match_candidate_materialize_dispatch (
+ GoodixMilanMatchCandidate *candidate);
diff --git a/libfprint/drivers/goodix53x5/milan/match/correspondence.c b/libfprint/drivers/goodix53x5/milan/match/correspondence.c
new file mode 100644
index 0000000..32d3733
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/correspondence.c
@@ -0,0 +1,1030 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan match correspondence
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/match/correspondence.h"
+#include "milan/preprocess/state.h"
+#include "milan/relations.h"
+#include "milan/transform-private.h"
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int
+milan_descriptor_distance (const GoodixMilanFeatureRecord *first,
+ const GoodixMilanFeatureRecord *second)
+{
+ const uint8_t *a = (const uint8_t *) first + 16;
+ const uint8_t *b = (const uint8_t *) second + 16;
+ int distance = 0;
+
+ for (size_t i = 0; i < 24; i++)
+ {
+ uint8_t value = a[i] ^ b[i];
+
+ while (value != 0)
+ {
+ value &= (uint8_t) (value - 1);
+ distance++;
+ }
+ }
+ return distance;
+}
+
+static int32_t
+milan_spatial_distance_squared_s32 (int32_t dx,
+ int32_t dy)
+{
+ return goodix_milan_transform_s32 (
+ (uint32_t) dx * (uint32_t) dx + (uint32_t) dy * (uint32_t) dy);
+}
+
+size_t
+goodix_milan_match_feature_records (const GoodixMilanFeatureRecord *prior,
+ size_t prior_count,
+ const GoodixMilanFeatureRecord *current,
+ size_t current_count,
+ MilanFeatureMatch matches[31])
+{
+ size_t match_count = 0;
+
+ for (size_t prior_index = 0; prior_index < prior_count; prior_index++)
+ {
+ int best_distance = 192;
+ int second_distance = 192;
+ int best_index = -1;
+
+ for (size_t current_index = 0; current_index < current_count;
+ current_index++)
+ {
+ int distance = milan_descriptor_distance (
+ &prior[prior_index], ¤t[current_index]);
+
+ if (distance < best_distance)
+ {
+ second_distance = best_distance;
+ best_distance = distance;
+ best_index = (int) current_index;
+ }
+ else if (distance < second_distance)
+ second_distance = distance;
+ }
+ if (best_index < 0 || best_distance * 40 >= second_distance * 38)
+ continue;
+
+ const uint16_t current_x = (uint16_t) current[best_index].refined_x;
+ const uint16_t current_y = (uint16_t) current[best_index].refined_y;
+ int replaced = 0;
+
+ for (size_t i = 0; i < match_count;)
+ {
+ const GoodixMilanFeatureRecord *selected =
+ ¤t[matches[i].current_index];
+ int32_t dx = (int32_t) current_x -
+ (int32_t) (uint16_t) selected->refined_x;
+ int32_t dy = (int32_t) current_y -
+ (int32_t) (uint16_t) selected->refined_y;
+
+ if (milan_spatial_distance_squared_s32 (dx, dy) >= 0x10000)
+ {
+ i++;
+ continue;
+ }
+ if (best_distance >= matches[i].best_distance)
+ {
+ if (!replaced)
+ {
+ replaced = -1;
+ break;
+ }
+ i++;
+ continue;
+ }
+ if (!replaced)
+ {
+ matches[i] = (MilanFeatureMatch) {
+ (int32_t) prior_index, best_index,
+ best_distance, second_distance,
+ };
+ replaced = 1;
+ i++;
+ }
+ else
+ {
+ matches[i] = matches[match_count - 1];
+ match_count--;
+ i++;
+ }
+ }
+ if (replaced != 0)
+ continue;
+ if (match_count == 31)
+ {
+ size_t worst = 0;
+
+ for (size_t i = 1; i < match_count; i++)
+ if (matches[i].best_distance > matches[worst].best_distance)
+ worst = i;
+ if (best_distance >= matches[worst].best_distance)
+ continue;
+ matches[worst] = (MilanFeatureMatch) {
+ (int32_t) prior_index, best_index,
+ best_distance, second_distance,
+ };
+ }
+ else
+ matches[match_count++] = (MilanFeatureMatch) {
+ (int32_t) prior_index, best_index,
+ best_distance, second_distance,
+ };
+ }
+ return match_count;
+}
+
+static int
+milan_descriptor_hamming64 (const uint8_t *source,
+ const uint8_t *target)
+{
+ uint64_t a, b;
+
+ memcpy (&a, source, sizeof (a));
+ memcpy (&b, target, sizeof (b));
+ return __builtin_popcountll (a ^ b);
+}
+
+static int
+milan_descriptor_hamming32 (const uint8_t *source,
+ const uint8_t *target)
+{
+ uint32_t a, b;
+
+ memcpy (&a, source, sizeof (a));
+ memcpy (&b, target, sizeof (b));
+ return __builtin_popcount (a ^ b);
+}
+
+static int
+milan_recognition_descriptor_details (const GoodixMilanFeatureRecord *enrolled,
+ const GoodixMilanFeatureRecord *probe,
+ int *normal_layout)
+{
+ const uint8_t *source = (const uint8_t *) enrolled;
+ const uint8_t *target = (const uint8_t *) probe;
+ int first = 0;
+ int second = 0;
+ int normal_tail = 0;
+ int shifted_tail = 0;
+
+ first = milan_descriptor_hamming64 (source + 16, target + 16);
+ if (first > 23)
+ return -1;
+
+ second = milan_descriptor_hamming64 (source + 24, target + 24);
+
+ int shifted = first - second + 64;
+ if (first + second > 47)
+ {
+ if (shifted > 47)
+ return -1;
+ normal_tail = 192;
+ }
+ else
+ {
+ normal_tail = milan_descriptor_hamming32 (source + 32, target + 32) +
+ milan_descriptor_hamming32 (source + 40, target + 40);
+ if (shifted > 47)
+ shifted_tail = 192;
+ }
+
+ if (shifted_tail != 192)
+ shifted_tail = milan_descriptor_hamming32 (source + 32, target + 36) +
+ milan_descriptor_hamming32 (source + 40, target + 48);
+
+ int normal_distance = first + second + normal_tail;
+ int shifted_distance = shifted + shifted_tail;
+ if (normal_layout)
+ *normal_layout = normal_distance < shifted_distance;
+ return normal_distance < shifted_distance ? normal_distance : shifted_distance;
+}
+
+static int
+milan_recognition_descriptor_distance (const GoodixMilanFeatureRecord *enrolled,
+ const GoodixMilanFeatureRecord *probe)
+{
+ return milan_recognition_descriptor_details (enrolled, probe, NULL);
+}
+
+int
+goodix_milan_match_correspondences_partitioned (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ size_t enrolled_partition_count,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ size_t probe_partition_count,
+ int32_t *pairs,
+ size_t pair_capacity,
+ size_t *pair_count,
+ const MilanMatchDistanceReduction *primary_reductions)
+{
+ MilanFeatureMatch matches[MILAN_MATCH_MAX_PAIRS];
+ size_t match_count = 0;
+
+ if (!enrolled_records || !probe_records || !pairs || !pair_count ||
+ enrolled_record_count == 0 || enrolled_record_count > 150 ||
+ probe_record_count == 0 || probe_record_count > 150 ||
+ enrolled_partition_count > enrolled_record_count ||
+ probe_partition_count > probe_record_count ||
+ pair_capacity < 31 || pair_capacity > MILAN_MATCH_MAX_PAIRS)
+ return -1;
+
+ for (size_t enrolled_index = 0;
+ enrolled_index < enrolled_record_count; enrolled_index++)
+ {
+ size_t probe_begin = enrolled_index < enrolled_partition_count
+ ? 0
+ : probe_partition_count;
+ size_t probe_end = enrolled_index < enrolled_partition_count
+ ? probe_partition_count
+ : probe_record_count;
+ int best_distance = 192;
+ int second_distance = 192;
+ int best_index = -1;
+
+ if (primary_reductions)
+ {
+ best_distance = primary_reductions[enrolled_index].best_distance;
+ second_distance = primary_reductions[enrolled_index].second_distance;
+ best_index = primary_reductions[enrolled_index].best_index;
+ }
+ else
+ {
+ for (size_t probe_index = probe_begin; probe_index < probe_end;
+ probe_index++)
+ {
+ int distance = milan_recognition_descriptor_distance (
+ &enrolled_records[enrolled_index], &probe_records[probe_index]);
+
+ if (distance < 0)
+ continue;
+ if (distance < best_distance)
+ {
+ second_distance = best_distance;
+ best_distance = distance;
+ best_index = (int) probe_index;
+ }
+ else if (distance < second_distance)
+ {
+ second_distance = distance;
+ }
+ }
+ }
+ if (best_index < 0 || best_distance * 40 >= second_distance * 38)
+ continue;
+
+ const uint16_t probe_x = (uint16_t) probe_records[best_index].refined_x;
+ const uint16_t probe_y = (uint16_t) probe_records[best_index].refined_y;
+ int replaced = 0;
+
+ for (size_t i = 0; i < match_count;)
+ {
+ const GoodixMilanFeatureRecord *selected =
+ &probe_records[matches[i].current_index];
+ int32_t dx = (int32_t) probe_x -
+ (int32_t) (uint16_t) selected->refined_x;
+ int32_t dy = (int32_t) probe_y -
+ (int32_t) (uint16_t) selected->refined_y;
+
+ if (milan_spatial_distance_squared_s32 (dx, dy) >= 0x10000)
+ {
+ i++;
+ continue;
+ }
+ if (best_distance >= matches[i].best_distance)
+ {
+ if (!replaced)
+ {
+ replaced = -1;
+ break;
+ }
+ i++;
+ continue;
+ }
+ if (!replaced)
+ {
+ matches[i] = (MilanFeatureMatch) {
+ (int32_t) enrolled_index, best_index,
+ best_distance, second_distance,
+ };
+ replaced = 1;
+ i++;
+ }
+ else
+ {
+ matches[i] = matches[match_count - 1];
+ match_count--;
+ i++;
+ }
+ }
+ if (replaced != 0)
+ continue;
+ if (match_count == pair_capacity)
+ {
+ size_t worst = 0;
+
+ for (size_t i = 1; i < match_count; i++)
+ if (matches[i].best_distance > matches[worst].best_distance)
+ worst = i;
+ if (best_distance >= matches[worst].best_distance)
+ continue;
+ matches[worst] = (MilanFeatureMatch) {
+ (int32_t) enrolled_index, best_index,
+ best_distance, second_distance,
+ };
+ }
+ else
+ matches[match_count++] = (MilanFeatureMatch) {
+ (int32_t) enrolled_index, best_index,
+ best_distance, second_distance,
+ };
+ }
+
+ for (size_t i = 0; i < pair_capacity; i++)
+ {
+ pairs[i * 2] = -1;
+ pairs[i * 2 + 1] = -1;
+ }
+ for (size_t i = 0; i < match_count; i++)
+ {
+ pairs[i * 2] = matches[i].prior_index;
+ pairs[i * 2 + 1] = matches[i].current_index;
+ }
+ *pair_count = match_count;
+ return 0;
+}
+
+size_t
+goodix_milan_match_relaxed_correspondences (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ size_t enrolled_partition_count,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ size_t probe_partition_count,
+ int32_t pairs[62],
+ MilanMatchDistanceReduction *primary_reductions)
+{
+ MilanFeatureMatch matches[31];
+ size_t match_count = 0;
+
+ if (primary_reductions)
+ for (size_t i = 0; i < enrolled_record_count; i++)
+ primary_reductions[i] = (MilanMatchDistanceReduction){ 192, 192, -1 };
+
+ for (size_t probe_index = 0; probe_index < probe_record_count; probe_index++)
+ {
+ size_t enrolled_begin = probe_index < probe_partition_count
+ ? 0
+ : enrolled_partition_count;
+ size_t enrolled_end = probe_index < probe_partition_count
+ ? enrolled_partition_count
+ : enrolled_record_count;
+ int best_distance = 192;
+ int second_distance = 192;
+ int best_index = -1;
+
+ for (size_t enrolled_index = enrolled_begin;
+ enrolled_index < enrolled_end; enrolled_index++)
+ {
+ int distance = milan_recognition_descriptor_distance (
+ &enrolled_records[enrolled_index], &probe_records[probe_index]);
+
+ if (distance < 0)
+ continue;
+ /* Each enrolled record still sees probe indices in ascending order. */
+ if (primary_reductions)
+ {
+ MilanMatchDistanceReduction *primary =
+ &primary_reductions[enrolled_index];
+
+ if (distance < primary->best_distance)
+ {
+ primary->second_distance = primary->best_distance;
+ primary->best_distance = distance;
+ primary->best_index = (int32_t) probe_index;
+ }
+ else if (distance < primary->second_distance)
+ {
+ primary->second_distance = distance;
+ }
+ }
+ if (distance < best_distance)
+ {
+ second_distance = best_distance;
+ best_distance = distance;
+ best_index = (int) enrolled_index;
+ }
+ else if (distance < second_distance)
+ second_distance = distance;
+ }
+ if (best_index < 0 || best_distance * 40 >= second_distance * 38)
+ continue;
+
+ uint16_t enrolled_x =
+ (uint16_t) enrolled_records[best_index].refined_x;
+ uint16_t enrolled_y =
+ (uint16_t) enrolled_records[best_index].refined_y;
+ int replaced = 0;
+
+ for (size_t i = 0; i < match_count;)
+ {
+ const GoodixMilanFeatureRecord *selected =
+ &enrolled_records[matches[i].prior_index];
+ int32_t dx = (int32_t) enrolled_x -
+ (int32_t) (uint16_t) selected->refined_x;
+ int32_t dy = (int32_t) enrolled_y -
+ (int32_t) (uint16_t) selected->refined_y;
+
+ if (milan_spatial_distance_squared_s32 (dx, dy) >= 0x10000)
+ {
+ i++;
+ continue;
+ }
+ if (best_distance >= matches[i].best_distance)
+ {
+ if (!replaced)
+ {
+ replaced = -1;
+ break;
+ }
+ i++;
+ continue;
+ }
+ if (!replaced)
+ {
+ matches[i] = (MilanFeatureMatch) {
+ best_index, (int32_t) probe_index,
+ best_distance, second_distance,
+ };
+ replaced = 1;
+ i++;
+ }
+ else
+ {
+ matches[i] = matches[match_count - 1];
+ match_count--;
+ i++;
+ }
+ }
+ if (replaced != 0)
+ continue;
+ if (match_count == 31)
+ {
+ size_t worst = 0;
+
+ for (size_t i = 1; i < match_count; i++)
+ if (matches[i].best_distance > matches[worst].best_distance)
+ worst = i;
+ if (best_distance >= matches[worst].best_distance)
+ continue;
+ matches[worst] = (MilanFeatureMatch) {
+ best_index, (int32_t) probe_index,
+ best_distance, second_distance,
+ };
+ }
+ else
+ matches[match_count++] = (MilanFeatureMatch) {
+ best_index, (int32_t) probe_index,
+ best_distance, second_distance,
+ };
+ }
+
+ for (size_t i = 0; i < 31; i++)
+ {
+ pairs[i * 2] = i < match_count ? matches[i].prior_index : -1;
+ pairs[i * 2 + 1] = i < match_count ? matches[i].current_index : -1;
+ }
+ return match_count;
+}
+
+static int32_t
+milan_match_scan_raw_s32 (int32_t first,
+ uint32_t first_coordinate,
+ int32_t second,
+ uint32_t second_coordinate,
+ int32_t translation)
+{
+ return goodix_milan_transform_affine_s32 (
+ first, first_coordinate, second, second_coordinate,
+ (uint32_t) translation << 8);
+}
+
+static int32_t
+milan_match_scan_round_pixel_s32 (int32_t value)
+{
+ int32_t rounded_q8 = goodix_milan_transform_sar32 (
+ (uint32_t) value + UINT32_C (0x80), 8);
+
+ return goodix_milan_transform_sar32 (
+ (uint32_t) rounded_q8 + UINT32_C (0x80), 8);
+}
+
+static int
+milan_match_scan_residual_within (int32_t mapped,
+ uint32_t expected)
+{
+ int32_t difference = goodix_milan_transform_s32 (
+ (uint32_t) mapped - expected);
+
+ if (difference <= 0)
+ difference = goodix_milan_transform_s32 (
+ expected - (uint32_t) mapped);
+ return difference <= 0x1500;
+}
+
+int
+goodix_milan_match_alternate_correspondences_internal (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ size_t enrolled_partition,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ size_t probe_partition,
+ const int32_t primary_transform[6],
+ int32_t *pairs,
+ size_t pair_capacity,
+ size_t *pair_count)
+{
+ MilanFeatureMatch matches[MILAN_MATCH_MAX_PAIRS];
+ int32_t inverse[6];
+ size_t match_count = 0;
+
+ if (!enrolled_records || !probe_records || !primary_transform || !pairs ||
+ !pair_count || enrolled_partition > enrolled_record_count ||
+ probe_partition > probe_record_count || pair_capacity == 0 ||
+ pair_capacity > MILAN_MATCH_MAX_PAIRS ||
+ goodix_milan_transform_invert_s32_checked (
+ primary_transform, inverse) != 0)
+ return -1;
+ for (size_t partition = 0; partition < 2; partition++)
+ {
+ size_t enrolled_begin = partition == 0 ? 0 : enrolled_partition;
+ size_t enrolled_end = partition == 0 ? enrolled_partition
+ : enrolled_record_count;
+ size_t probe_begin = partition == 0 ? 0 : probe_partition;
+ size_t probe_end = partition == 0 ? probe_partition : probe_record_count;
+
+ for (size_t enrolled_index = enrolled_begin;
+ enrolled_index < enrolled_end; enrolled_index++)
+ {
+ int32_t enrolled_x =
+ (uint16_t) enrolled_records[enrolled_index].refined_x;
+ int32_t enrolled_y =
+ (uint16_t) enrolled_records[enrolled_index].refined_y;
+ int32_t inverse_x = milan_match_scan_round_pixel_s32 (
+ milan_match_scan_raw_s32 (
+ inverse[0], (uint32_t) enrolled_x,
+ inverse[1], (uint32_t) enrolled_y, inverse[2]));
+ int32_t inverse_y = milan_match_scan_round_pixel_s32 (
+ milan_match_scan_raw_s32 (
+ inverse[3], (uint32_t) enrolled_x,
+ inverse[4], (uint32_t) enrolled_y, inverse[5]));
+ int best_distance = 192;
+ int second_distance = 192;
+ int best_index = -1;
+
+ if (inverse_x <= 5 ||
+ inverse_x >= GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS - 5 ||
+ inverse_y <= 5 ||
+ inverse_y >= GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS - 5)
+ continue;
+ for (size_t probe_index = probe_begin; probe_index < probe_end;
+ probe_index++)
+ {
+ int distance = milan_recognition_descriptor_distance (
+ &enrolled_records[enrolled_index], &probe_records[probe_index]);
+ int32_t probe_x =
+ (uint16_t) probe_records[probe_index].refined_x;
+ int32_t probe_y =
+ (uint16_t) probe_records[probe_index].refined_y;
+ int32_t raw_x = milan_match_scan_raw_s32 (
+ primary_transform[0], (uint32_t) probe_x,
+ primary_transform[1], (uint32_t) probe_y,
+ primary_transform[2]);
+ int32_t raw_y = milan_match_scan_raw_s32 (
+ primary_transform[3], (uint32_t) probe_x,
+ primary_transform[4], (uint32_t) probe_y,
+ primary_transform[5]);
+ int32_t transformed_x = goodix_milan_transform_sar32 (
+ (uint32_t) raw_x, 8);
+ int32_t transformed_y = goodix_milan_transform_sar32 (
+ (uint32_t) raw_y, 8);
+ int32_t pixel_x = milan_match_scan_round_pixel_s32 (raw_x);
+ int32_t pixel_y = milan_match_scan_round_pixel_s32 (raw_y);
+
+ if (distance < 0 ||
+ !milan_match_scan_residual_within (
+ transformed_x, (uint32_t) enrolled_x) ||
+ !milan_match_scan_residual_within (
+ transformed_y, (uint32_t) enrolled_y) ||
+ pixel_x <= 5 ||
+ pixel_x > GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS - 5 ||
+ pixel_y <= 5 ||
+ pixel_y > GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS - 5)
+ continue;
+ if (distance < best_distance)
+ {
+ second_distance = best_distance;
+ best_distance = distance;
+ best_index = (int) probe_index;
+ }
+ else if (distance < second_distance)
+ second_distance = distance;
+ }
+ if (best_index < 0 || best_distance * 40 >= second_distance * 38)
+ continue;
+
+ uint16_t probe_x =
+ (uint16_t) probe_records[best_index].refined_x;
+ uint16_t probe_y =
+ (uint16_t) probe_records[best_index].refined_y;
+ int replaced = 0;
+ for (size_t i = 0; i < match_count;)
+ {
+ const GoodixMilanFeatureRecord *selected =
+ &probe_records[matches[i].current_index];
+ int32_t dx = (int32_t) probe_x -
+ (int32_t) (uint16_t) selected->refined_x;
+ int32_t dy = (int32_t) probe_y -
+ (int32_t) (uint16_t) selected->refined_y;
+
+ if (milan_spatial_distance_squared_s32 (dx, dy) >= 0x10000)
+ {
+ i++;
+ continue;
+ }
+ if (best_distance >= matches[i].best_distance)
+ {
+ if (!replaced)
+ {
+ replaced = -1;
+ break;
+ }
+ i++;
+ continue;
+ }
+ if (!replaced)
+ {
+ matches[i] = (MilanFeatureMatch) {
+ (int32_t) enrolled_index, best_index,
+ best_distance, second_distance,
+ };
+ replaced = 1;
+ i++;
+ }
+ else
+ {
+ matches[i] = matches[match_count - 1];
+ match_count--;
+ }
+ }
+ if (replaced != 0)
+ continue;
+ if (match_count == pair_capacity)
+ {
+ size_t worst = 0;
+
+ for (size_t i = 1; i < match_count; i++)
+ if (matches[i].best_distance > matches[worst].best_distance)
+ worst = i;
+ if (best_distance >= matches[worst].best_distance)
+ continue;
+ matches[worst] = (MilanFeatureMatch) {
+ (int32_t) enrolled_index, best_index,
+ best_distance, second_distance,
+ };
+ }
+ else
+ matches[match_count++] = (MilanFeatureMatch) {
+ (int32_t) enrolled_index, best_index,
+ best_distance, second_distance,
+ };
+ }
+ }
+
+ for (size_t i = 0; i < pair_capacity; i++)
+ {
+ pairs[i * 2] = i < match_count ? matches[i].prior_index : -1;
+ pairs[i * 2 + 1] = i < match_count ? matches[i].current_index : -1;
+ }
+ *pair_count = match_count;
+ return 0;
+}
+
+static int
+milan_cross_class_descriptor_distance (
+ const GoodixMilanFeatureRecord *enrolled,
+ const GoodixMilanFeatureRecord *probe,
+ int32_t tail_hamming_limit)
+{
+ const uint8_t *source = (const uint8_t *) enrolled;
+ const uint8_t *target = (const uint8_t *) probe;
+ int normal_layout;
+ int distance = 0;
+
+ if (milan_recognition_descriptor_details (
+ enrolled, probe, &normal_layout) < 0)
+ return -1;
+ size_t target_offset = normal_layout ? 40 : 48;
+ for (size_t i = 0; i < 8; i++)
+ distance += __builtin_popcount (
+ (unsigned) (source[40 + i] ^ target[target_offset + i]));
+ return distance <= tail_hamming_limit ? distance : -1;
+}
+
+static int
+milan_tail_descriptor_distance (const GoodixMilanFeatureRecord *enrolled,
+ const GoodixMilanFeatureRecord *probe,
+ int32_t hamming_limit)
+{
+ const uint8_t *source = (const uint8_t *) enrolled;
+ const uint8_t *target = (const uint8_t *) probe;
+ int normal = 0;
+ int shifted = 0;
+
+ for (size_t i = 0; i < 8; i++)
+ {
+ normal += __builtin_popcount (
+ (unsigned) (source[40 + i] ^ target[40 + i]));
+ shifted += __builtin_popcount (
+ (unsigned) (source[40 + i] ^ target[48 + i]));
+ }
+ int distance = normal < shifted ? normal : shifted;
+ return distance <= hamming_limit ? distance : -1;
+}
+
+static void
+milan_store_cross_class_match (
+ MilanFeatureMatch matches[MILAN_MATCH_MAX_PAIRS],
+ size_t *match_count,
+ const GoodixMilanFeatureRecord *probe_records,
+ int32_t enrolled_index,
+ int32_t probe_index,
+ int32_t best_distance,
+ int32_t second_distance,
+ size_t pair_capacity)
+{
+ uint16_t probe_x = (uint16_t) probe_records[probe_index].refined_x;
+ uint16_t probe_y = (uint16_t) probe_records[probe_index].refined_y;
+ int replaced = 0;
+
+ for (size_t i = 0; i < *match_count;)
+ {
+ const GoodixMilanFeatureRecord *selected =
+ &probe_records[matches[i].current_index];
+ int32_t dx = (int32_t) probe_x -
+ (int32_t) (uint16_t) selected->refined_x;
+ int32_t dy = (int32_t) probe_y -
+ (int32_t) (uint16_t) selected->refined_y;
+
+ if (milan_spatial_distance_squared_s32 (dx, dy) >= 0x10000)
+ {
+ i++;
+ continue;
+ }
+ if (best_distance >= matches[i].best_distance)
+ {
+ if (!replaced)
+ {
+ replaced = -1;
+ break;
+ }
+ i++;
+ continue;
+ }
+ if (!replaced)
+ {
+ matches[i] = (MilanFeatureMatch) {
+ enrolled_index, probe_index, best_distance, second_distance,
+ };
+ replaced = 1;
+ i++;
+ }
+ else
+ {
+ matches[i] = matches[*match_count - 1];
+ (*match_count)--;
+ i++;
+ }
+ }
+ if (replaced != 0)
+ return;
+ if (*match_count == pair_capacity)
+ {
+ size_t worst = 0;
+
+ for (size_t i = 1; i < *match_count; i++)
+ if (matches[i].best_distance > matches[worst].best_distance)
+ worst = i;
+ if (best_distance >= matches[worst].best_distance)
+ return;
+ matches[worst] = (MilanFeatureMatch) {
+ enrolled_index, probe_index, best_distance, second_distance,
+ };
+ }
+ else
+ matches[(*match_count)++] = (MilanFeatureMatch) {
+ enrolled_index, probe_index, best_distance, second_distance,
+ };
+}
+
+size_t
+goodix_milan_match_cross_class_correspondences (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ size_t enrolled_partition_count,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ size_t probe_partition_count,
+ uint8_t enrolled_class,
+ int32_t tail_hamming_limit,
+ int32_t *pairs,
+ size_t pair_capacity)
+{
+ MilanFeatureMatch matches[MILAN_MATCH_MAX_PAIRS];
+ size_t match_count = 0;
+
+ for (size_t enrolled_index = 0;
+ enrolled_index < enrolled_record_count; enrolled_index++)
+ {
+ const uint8_t *enrolled =
+ (const uint8_t *) &enrolled_records[enrolled_index];
+ size_t probe_begin = enrolled_index < enrolled_partition_count
+ ? 0
+ : probe_partition_count;
+ size_t probe_end = enrolled_index < enrolled_partition_count
+ ? probe_partition_count
+ : probe_record_count;
+ int best_distance = 192;
+ int second_distance = 192;
+ int best_index = -1;
+
+ if (enrolled[12] != enrolled_class)
+ continue;
+ for (size_t probe_index = probe_begin; probe_index < probe_end;
+ probe_index++)
+ {
+ const uint8_t *probe =
+ (const uint8_t *) &probe_records[probe_index];
+ int distance;
+
+ if (probe[12] != (enrolled_class == 1 ? 2 : 1))
+ continue;
+ distance = milan_cross_class_descriptor_distance (
+ &enrolled_records[enrolled_index], &probe_records[probe_index],
+ tail_hamming_limit);
+ if (distance < 0)
+ continue;
+ if (distance < best_distance)
+ {
+ second_distance = best_distance;
+ best_distance = distance;
+ best_index = (int) probe_index;
+ }
+ else if (distance < second_distance)
+ second_distance = distance;
+ }
+ if (best_index < 0 || best_distance * 40 >= second_distance * 38)
+ continue;
+ milan_store_cross_class_match (
+ matches, &match_count, probe_records, (int32_t) enrolled_index,
+ best_index, best_distance, second_distance, pair_capacity);
+ }
+
+ for (size_t i = 0; i < pair_capacity; i++)
+ {
+ pairs[i * 2] = i < match_count ? matches[i].prior_index : -1;
+ pairs[i * 2 + 1] = i < match_count ? matches[i].current_index : -1;
+ }
+ return match_count;
+}
+
+size_t
+goodix_milan_match_cross_class_alternate_correspondences (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ size_t enrolled_partition_count,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ size_t probe_partition_count,
+ const int32_t primary_transform[6],
+ int32_t sibling_tail_hamming_limit,
+ int32_t *pairs,
+ size_t pair_capacity)
+{
+ MilanFeatureMatch matches[MILAN_MATCH_MAX_PAIRS];
+ int32_t inverse[6];
+ size_t match_count = 0;
+
+ for (size_t i = 0; i < pair_capacity; i++)
+ {
+ pairs[i * 2] = -1;
+ pairs[i * 2 + 1] = -1;
+ }
+ if (goodix_milan_transform_invert_s32_checked (
+ primary_transform, inverse) != 0)
+ return 0;
+
+ for (size_t enrolled_index = 0;
+ enrolled_index < enrolled_record_count; enrolled_index++)
+ {
+ int32_t enrolled_x =
+ (uint16_t) enrolled_records[enrolled_index].refined_x;
+ int32_t enrolled_y =
+ (uint16_t) enrolled_records[enrolled_index].refined_y;
+ int32_t inverse_x = milan_match_scan_round_pixel_s32 (
+ milan_match_scan_raw_s32 (
+ inverse[0], (uint32_t) enrolled_x,
+ inverse[1], (uint32_t) enrolled_y, inverse[2]));
+ int32_t inverse_y = milan_match_scan_round_pixel_s32 (
+ milan_match_scan_raw_s32 (
+ inverse[3], (uint32_t) enrolled_x,
+ inverse[4], (uint32_t) enrolled_y, inverse[5]));
+ size_t probe_begin = enrolled_index < enrolled_partition_count
+ ? 0
+ : probe_partition_count;
+ size_t probe_end = enrolled_index < enrolled_partition_count
+ ? probe_partition_count
+ : probe_record_count;
+ int best_distance = 192;
+ int second_distance = 192;
+ int best_index = -1;
+
+ if (inverse_x <= 5 ||
+ inverse_x >= GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS - 5 ||
+ inverse_y <= 5 ||
+ inverse_y >= GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS - 5)
+ continue;
+ for (size_t probe_index = probe_begin; probe_index < probe_end;
+ probe_index++)
+ {
+ int distance = milan_tail_descriptor_distance (
+ &enrolled_records[enrolled_index], &probe_records[probe_index],
+ sibling_tail_hamming_limit);
+ int32_t probe_x = (uint16_t) probe_records[probe_index].refined_x;
+ int32_t probe_y = (uint16_t) probe_records[probe_index].refined_y;
+ int32_t raw_x = milan_match_scan_raw_s32 (
+ primary_transform[0], (uint32_t) probe_x,
+ primary_transform[1], (uint32_t) probe_y,
+ primary_transform[2]);
+ int32_t raw_y = milan_match_scan_raw_s32 (
+ primary_transform[3], (uint32_t) probe_x,
+ primary_transform[4], (uint32_t) probe_y,
+ primary_transform[5]);
+ int32_t transformed_x = goodix_milan_transform_sar32 (
+ (uint32_t) raw_x, 8);
+ int32_t transformed_y = goodix_milan_transform_sar32 (
+ (uint32_t) raw_y, 8);
+ int32_t pixel_x = milan_match_scan_round_pixel_s32 (raw_x);
+ int32_t pixel_y = milan_match_scan_round_pixel_s32 (raw_y);
+
+ if (distance < 0 ||
+ !milan_match_scan_residual_within (
+ transformed_x, (uint32_t) enrolled_x) ||
+ !milan_match_scan_residual_within (
+ transformed_y, (uint32_t) enrolled_y) ||
+ pixel_x <= 5 ||
+ pixel_x > GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS - 5 ||
+ pixel_y <= 5 ||
+ pixel_y > GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS - 5)
+ continue;
+ if (distance < best_distance)
+ {
+ second_distance = best_distance;
+ best_distance = distance;
+ best_index = (int) probe_index;
+ }
+ else if (distance < second_distance)
+ second_distance = distance;
+ }
+ if (best_index < 0 || best_distance * 40 >= second_distance * 38)
+ continue;
+ milan_store_cross_class_match (
+ matches, &match_count, probe_records, (int32_t) enrolled_index,
+ best_index, best_distance, second_distance, pair_capacity);
+ }
+
+ for (size_t i = 0; i < pair_capacity; i++)
+ {
+ pairs[i * 2] = i < match_count ? matches[i].prior_index : -1;
+ pairs[i * 2 + 1] = i < match_count ? matches[i].current_index : -1;
+ }
+ return match_count;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/match/correspondence.h b/libfprint/drivers/goodix53x5/milan/match/correspondence.h
new file mode 100644
index 0000000..2350693
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/correspondence.h
@@ -0,0 +1,94 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan match correspondence internals
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include "milan/milan.h"
+
+#define MILAN_MATCH_MAX_PAIRS 42
+#define MILAN_MATCH_DESCRIPTOR_DISTANCE_LIMIT 23
+
+typedef struct
+{
+ int32_t prior_index;
+ int32_t current_index;
+ int32_t best_distance;
+ int32_t second_distance;
+} MilanFeatureMatch;
+
+typedef struct
+{
+ int32_t best_distance;
+ int32_t second_distance;
+ int32_t best_index;
+} MilanMatchDistanceReduction;
+
+size_t goodix_milan_match_feature_records (
+ const GoodixMilanFeatureRecord *prior,
+ size_t prior_count,
+ const GoodixMilanFeatureRecord *current,
+ size_t current_count,
+ MilanFeatureMatch matches[31]);
+
+int goodix_milan_match_correspondences_partitioned (const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ size_t enrolled_partition_count,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ size_t probe_partition_count,
+ int32_t *pairs,
+ size_t pair_capacity,
+ size_t *pair_count,
+ const MilanMatchDistanceReduction *primary_reductions);
+
+size_t goodix_milan_match_relaxed_correspondences (const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ size_t enrolled_partition_count,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ size_t probe_partition_count,
+ int32_t pairs[62],
+ MilanMatchDistanceReduction *primary_reductions);
+
+int goodix_milan_match_alternate_correspondences_internal (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ size_t enrolled_partition,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ size_t probe_partition,
+ const int32_t primary_transform[6],
+ int32_t *pairs,
+ size_t pair_capacity,
+ size_t *pair_count);
+
+size_t goodix_milan_match_cross_class_correspondences (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ size_t enrolled_partition_count,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ size_t probe_partition_count,
+ uint8_t enrolled_class,
+ int32_t tail_hamming_limit,
+ int32_t *pairs,
+ size_t pair_capacity);
+
+size_t goodix_milan_match_cross_class_alternate_correspondences (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ size_t enrolled_partition_count,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ size_t probe_partition_count,
+ const int32_t primary_transform[6],
+ int32_t sibling_tail_hamming_limit,
+ int32_t *pairs,
+ size_t pair_capacity);
diff --git a/libfprint/drivers/goodix53x5/milan/match/fallback.c b/libfprint/drivers/goodix53x5/milan/match/fallback.c
new file mode 100644
index 0000000..4ce90df
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/fallback.c
@@ -0,0 +1,112 @@
+/*
+ * Goodix 53x5 driver for libfprint - rejection fallback finalization
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/match/fallback.h"
+
+void
+goodix_milan_match_fallback_reset (GoodixMilanMatchFallback *fallback)
+{
+ memset (fallback, 0, sizeof(*fallback));
+ fallback->winner.feature = -1;
+}
+
+int
+goodix_milan_match_fallback_store (
+ GoodixMilanMatchFallback *fallback,
+ int32_t feature,
+ int32_t enabled,
+ const int32_t pairs[GOODIX_MILAN_MATCH_FALLBACK_PAIR_CAPACITY * 2],
+ size_t pair_count)
+{
+ GoodixMilanMatchFallbackWorkspace *workspace;
+
+ if (!fallback || !pairs ||
+ fallback->workspace_count == GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT ||
+ pair_count > GOODIX_MILAN_MATCH_FALLBACK_PAIR_CAPACITY)
+ return -1;
+ workspace = &fallback->workspaces[fallback->workspace_count++];
+ workspace->feature = feature;
+ workspace->enabled = enabled;
+ workspace->pair_count = pair_count;
+ memcpy (workspace->pairs, pairs, sizeof(workspace->pairs));
+ return 0;
+}
+
+int
+goodix_milan_match_fallback_consider (
+ GoodixMilanMatchFallback *fallback,
+ int32_t feature,
+ int32_t filtered_count,
+ int32_t transform_classifier,
+ int32_t overlap,
+ int32_t overlap_threshold,
+ int32_t raw_detail,
+ int32_t coverage,
+ int32_t penalty_enabled,
+ int32_t average_scale,
+ int32_t absolute_dot_q16,
+ const int32_t transform[6])
+{
+ GoodixMilanMatchFallbackWinner current;
+
+ if (!fallback || !transform)
+ return -1;
+ if (filtered_count <= 4 || transform_classifier != 0)
+ return 0;
+
+ fallback->geometry_seen = 1;
+ if (overlap <= overlap_threshold || raw_detail <= 195)
+ return 0;
+
+ current = (GoodixMilanMatchFallbackWinner) {
+ .feature = feature,
+ .filtered_count = filtered_count,
+ .overlap = overlap,
+ .raw_detail = raw_detail,
+ .coverage = coverage,
+ .adjusted_detail = raw_detail,
+ };
+ memcpy (current.transform, transform, sizeof(current.transform));
+ if (penalty_enabled)
+ {
+ current.adjusted_detail -=
+ 4 * ((uint32_t) (average_scale - 234) > 47);
+ current.adjusted_detail -= 4 * (absolute_dot_q16 >= 0x147b);
+ }
+
+ fallback->count_sum += filtered_count;
+ if (current.adjusted_detail > fallback->best_adjusted_detail)
+ fallback->best_adjusted_detail = current.adjusted_detail;
+ if (!fallback->winner_valid ||
+ current.adjusted_detail > fallback->winner.adjusted_detail ||
+ (current.adjusted_detail == fallback->winner.adjusted_detail &&
+ current.filtered_count > fallback->winner.filtered_count) ||
+ (current.adjusted_detail == fallback->winner.adjusted_detail &&
+ current.filtered_count == fallback->winner.filtered_count &&
+ current.coverage > fallback->winner.coverage))
+ {
+ fallback->winner = current;
+ fallback->winner_valid = 1;
+ }
+ return 1;
+}
+
+int32_t
+goodix_milan_match_fallback_rejection_score (
+ const GoodixMilanMatchFallback *fallback)
+{
+ int32_t reason = (fallback->count_sum < 6) << 2;
+
+ if (fallback->geometry_seen && fallback->best_adjusted_detail < 208)
+ reason |= 2;
+ if (fallback->geometry_seen && fallback->winner.coverage < 128)
+ reason |= 1;
+ return -reason;
+}
diff --git a/libfprint/drivers/goodix53x5/milan/match/fallback.h b/libfprint/drivers/goodix53x5/milan/match/fallback.h
new file mode 100644
index 0000000..e0411ae
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/fallback.h
@@ -0,0 +1,80 @@
+/*
+ * Goodix 53x5 driver for libfprint - rejection fallback finalization
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+
+#include "milan/capacity.h"
+
+#define GOODIX_MILAN_MATCH_FALLBACK_PAIR_CAPACITY 31
+
+typedef struct
+{
+ int32_t feature;
+ int32_t enabled;
+ size_t pair_count;
+ int32_t pairs[GOODIX_MILAN_MATCH_FALLBACK_PAIR_CAPACITY * 2];
+} GoodixMilanMatchFallbackWorkspace;
+
+typedef struct
+{
+ int32_t feature;
+ int32_t filtered_count;
+ int32_t overlap;
+ int32_t raw_detail;
+ int32_t coverage;
+ int32_t adjusted_detail;
+ int32_t transform[6];
+} GoodixMilanMatchFallbackWinner;
+
+typedef struct
+{
+ GoodixMilanMatchFallbackWorkspace
+ workspaces[GOODIX_MILAN_PROFILE9_ACTIVE_FEATURE_LIMIT];
+ size_t workspace_count;
+ int32_t geometry_seen;
+ int32_t count_sum;
+ int32_t best_adjusted_detail;
+ GoodixMilanMatchFallbackWinner winner;
+ int winner_valid;
+} GoodixMilanMatchFallback;
+
+void
+goodix_milan_match_fallback_reset (GoodixMilanMatchFallback *fallback);
+
+int
+goodix_milan_match_fallback_store (
+ GoodixMilanMatchFallback *fallback,
+ int32_t feature,
+ int32_t enabled,
+ const int32_t pairs[GOODIX_MILAN_MATCH_FALLBACK_PAIR_CAPACITY * 2],
+ size_t pair_count);
+
+int
+goodix_milan_match_fallback_consider (
+ GoodixMilanMatchFallback *fallback,
+ int32_t feature,
+ int32_t filtered_count,
+ int32_t transform_classifier,
+ int32_t overlap,
+ int32_t overlap_threshold,
+ int32_t raw_detail,
+ int32_t coverage,
+ int32_t penalty_enabled,
+ int32_t average_scale,
+ int32_t absolute_dot_q16,
+ const int32_t transform[6]);
+
+int32_t
+goodix_milan_match_fallback_rejection_score (
+ const GoodixMilanMatchFallback *fallback);
diff --git a/libfprint/drivers/goodix53x5/milan/match/geometry.c b/libfprint/drivers/goodix53x5/milan/match/geometry.c
new file mode 100644
index 0000000..051de96
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/geometry.c
@@ -0,0 +1,1225 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan match geometry
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#include "milan/match/geometry.h"
+#include "milan/match/correspondence.h"
+#include "milan/preprocess/state.h"
+#include "milan/private.h"
+#include "milan/relations.h"
+
+#include <limits.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+enum
+{
+ MILAN_AFFINE_Q8_ONE = 0x100,
+ MILAN_AFFINE_Q8_HALF = 0x80,
+ MILAN_AFFINE_Q8_SHIFT = 8,
+ MILAN_AFFINE_SOLVE_SHIFT = 10,
+ MILAN_AFFINE_SOLVE_SCALE = 1024,
+ MILAN_ORIENTATION_HALF_PERIOD = 0x1922,
+ MILAN_ORIENTATION_PERIOD = 0x3244,
+ MILAN_ORIENTATION_FULL_PERIOD = 0x6488,
+ MILAN_TRIANGLE_ORIENTATION_TOLERANCE = 0x400,
+ MILAN_TRIANGLE_AFFINE_SYMMETRY_TOLERANCE = 0x32,
+ MILAN_TRIANGLE_AFFINE_COEFFICIENT_LIMIT = 300,
+ MILAN_TRIANGLE_MINIMUM_EDGE_SQUARED = 0x2ffff,
+ MILAN_RECOGNITION_TRIANGLE_LIMIT = 0x3b2,
+ MILAN_RECOGNITION_NO_MODEL_RESIDUAL = 0x190000,
+ MILAN_RECOGNITION_INLIER_AXIS_LIMIT = 0x281,
+ MILAN_RECOGNITION_INLIER_SQUARED_LIMIT = 0x64000,
+ MILAN_RECOGNITION_ORIENTATION_LIMIT = 0x506,
+ MILAN_RECOGNITION_EARLY_INLIER_COUNT = 20,
+ MILAN_RECOGNITION_REFINE_INLIER_COUNT = 3,
+ MILAN_RECOGNITION_REFINE_RESIDUAL = 0x4000,
+};
+
+static void
+milan_affine_from_three_points (const int32_t source[6],
+ const int32_t target[6],
+ int32_t affine[6])
+{
+ int64_t determinant;
+ int64_t raw_a;
+ int64_t raw_b;
+ int64_t raw_c;
+ int64_t raw_d;
+
+ determinant =
+ (int64_t) (source[0] - source[2]) * (source[3] - source[5]) -
+ (int64_t) (source[2] - source[4]) * (source[1] - source[3]);
+ if (determinant == 0)
+ {
+ raw_a = INT32_MAX;
+ raw_b = INT32_MAX;
+ }
+ else
+ {
+ raw_a =
+ ((int64_t) (target[0] - target[2]) * MILAN_AFFINE_SOLVE_SCALE *
+ (source[3] - source[5]) -
+ (int64_t) (target[2] - target[4]) * MILAN_AFFINE_SOLVE_SCALE *
+ (source[1] - source[3])) /
+ determinant;
+ raw_b =
+ ((int64_t) (target[0] - target[2]) * MILAN_AFFINE_SOLVE_SCALE *
+ (source[2] - source[4]) -
+ (int64_t) (target[2] - target[4]) * MILAN_AFFINE_SOLVE_SCALE *
+ (source[0] - source[2])) /
+ -determinant;
+ }
+ raw_a = (int32_t) raw_a;
+ raw_b = (int32_t) raw_b;
+ affine[0] = (int32_t) raw_a >> 2;
+ affine[1] = (int32_t) raw_b >> 2;
+ affine[2] = (int32_t) ((((int64_t) target[0] << MILAN_AFFINE_SOLVE_SHIFT) -
+ raw_b * source[1] - raw_a * source[0]) >>
+ MILAN_AFFINE_SOLVE_SHIFT);
+
+ determinant =
+ (int64_t) (source[2] - source[0]) * (source[5] - source[1]) -
+ (int64_t) (source[4] - source[0]) * (source[3] - source[1]);
+ if (determinant == 0)
+ {
+ raw_c = INT32_MAX;
+ raw_d = INT32_MAX;
+ }
+ else
+ {
+ raw_c =
+ ((int64_t) (target[3] - target[1]) * MILAN_AFFINE_SOLVE_SCALE *
+ (source[5] - source[1]) -
+ (int64_t) (target[5] - target[1]) * MILAN_AFFINE_SOLVE_SCALE *
+ (source[3] - source[1])) /
+ determinant;
+ raw_d =
+ ((int64_t) (target[3] - target[1]) * MILAN_AFFINE_SOLVE_SCALE *
+ (source[4] - source[0]) -
+ (int64_t) (target[5] - target[1]) * MILAN_AFFINE_SOLVE_SCALE *
+ (source[2] - source[0])) /
+ -determinant;
+ }
+ raw_c = (int32_t) raw_c;
+ raw_d = (int32_t) raw_d;
+ affine[3] = (int32_t) raw_c >> 2;
+ affine[4] = (int32_t) raw_d >> 2;
+ affine[5] = (int32_t) ((((int64_t) target[5] << MILAN_AFFINE_SOLVE_SHIFT) -
+ raw_d * source[5] - raw_c * source[4]) >>
+ MILAN_AFFINE_SOLVE_SHIFT);
+}
+
+static int
+milan_affine_is_valid (const int32_t affine[6])
+{
+ int64_t a = affine[0];
+ int64_t b = affine[1];
+ int64_t c = affine[3];
+ int64_t d = affine[4];
+ /* Native sign-extends each wrapped dword product before the qword sum. */
+ int64_t first = (int64_t) (int32_t) (a * a) + (int32_t) (b * b);
+ int64_t cross = (int64_t) (int32_t) (a * c) + (int32_t) (b * d);
+ int64_t second = (int64_t) (int32_t) (c * c) + (int32_t) (d * d);
+ int64_t trace = first + second;
+ int64_t discriminant = (int64_t) (
+ (uint64_t) trace * (uint64_t) trace +
+ UINT64_C (4) * ((uint64_t) cross * (uint64_t) cross -
+ (uint64_t) first * (uint64_t) second));
+ int64_t lower = ((int64_t) 163 << 9) - trace;
+ int64_t upper = ((int64_t) 401 << 9) - trace;
+
+ return discriminant >= 0 && trace >= 0 && lower < 1 && upper >= 0 &&
+ lower * lower != discriminant && discriminant <= lower * lower &&
+ upper * upper != discriminant && discriminant <= upper * upper;
+}
+
+static int32_t
+milan_reinterpret_uint32_as_int32 (uint32_t value)
+{
+ int32_t result;
+
+ memcpy (&result, &value, sizeof(result));
+ return result;
+}
+
+static int32_t
+milan_triangle_shift_right_two (uint32_t value)
+{
+ uint32_t shifted = value >> 2;
+
+ if (value & UINT32_C (0x80000000))
+ shifted |= UINT32_C (0xc0000000);
+ return milan_reinterpret_uint32_as_int32 (shifted);
+}
+
+static int32_t
+milan_triangle_distance_shift_then_add (int32_t first_x,
+ int32_t first_y,
+ int32_t second_x,
+ int32_t second_y)
+{
+ uint32_t dx = (uint32_t) first_x - (uint32_t) second_x;
+ uint32_t dy = (uint32_t) first_y - (uint32_t) second_y;
+ uint32_t distance =
+ (uint32_t) milan_triangle_shift_right_two (dx * dx) +
+ (uint32_t) milan_triangle_shift_right_two (dy * dy);
+
+ return milan_reinterpret_uint32_as_int32 (distance);
+}
+
+static int32_t
+milan_triangle_distance_add_then_shift (int32_t first_x,
+ int32_t first_y,
+ int32_t second_x,
+ int32_t second_y)
+{
+ uint32_t dx = (uint32_t) first_x - (uint32_t) second_x;
+ uint32_t dy = (uint32_t) first_y - (uint32_t) second_y;
+
+ return milan_triangle_shift_right_two (dx * dx + dy * dy);
+}
+
+static int
+milan_triangle_edge_is_consistent (int32_t source_distance,
+ int32_t target_distance)
+{
+ return milan_reinterpret_uint32_as_int32 (
+ (uint32_t) source_distance * UINT32_C (5)) <=
+ milan_reinterpret_uint32_as_int32 (
+ (uint32_t) target_distance * UINT32_C (6)) &&
+ milan_reinterpret_uint32_as_int32 (
+ (uint32_t) target_distance * UINT32_C (5)) <=
+ milan_reinterpret_uint32_as_int32 (
+ (uint32_t) source_distance * UINT32_C (6)) &&
+ source_distance > MILAN_TRIANGLE_MINIMUM_EDGE_SQUARED &&
+ target_distance > MILAN_TRIANGLE_MINIMUM_EDGE_SQUARED;
+}
+
+static int32_t
+milan_normalize_orientation_difference (int32_t difference,
+ int32_t half_period,
+ int32_t period)
+{
+ if (difference > half_period)
+ difference -= period;
+ if (difference < -half_period)
+ difference += period;
+ return difference;
+}
+
+static int
+milan_triangle_orientations_are_consistent (int32_t differences[3])
+{
+ const int32_t half_period = MILAN_ORIENTATION_HALF_PERIOD;
+ const int32_t period = MILAN_ORIENTATION_PERIOD;
+ const int32_t tolerance = MILAN_TRIANGLE_ORIENTATION_TOLERANCE;
+
+ for (size_t retry = 0; retry < 2; retry++)
+ {
+ int32_t average =
+ (differences[0] + differences[1] + differences[2]) / 3;
+ int consistent = 1;
+
+ for (size_t i = 0; i < 3; i++)
+ consistent &= differences[i] - average <= tolerance &&
+ differences[i] - average >= -tolerance;
+ if (consistent)
+ return 1;
+ for (size_t i = 0; i < 3; i++)
+ differences[i] = milan_normalize_orientation_difference (
+ differences[i] + half_period, half_period, period);
+ }
+ return 0;
+}
+
+static int
+milan_triangle_affine_is_consistent (const int32_t affine[6])
+{
+ return abs (affine[0] - affine[4]) <
+ MILAN_TRIANGLE_AFFINE_SYMMETRY_TOLERANCE &&
+ abs (affine[3] + affine[1]) <
+ MILAN_TRIANGLE_AFFINE_SYMMETRY_TOLERANCE &&
+ abs (affine[0]) < MILAN_TRIANGLE_AFFINE_COEFFICIENT_LIMIT &&
+ abs (affine[3]) < MILAN_TRIANGLE_AFFINE_COEFFICIENT_LIMIT &&
+ abs (affine[4]) < MILAN_TRIANGLE_AFFINE_COEFFICIENT_LIMIT &&
+ abs (affine[1]) < MILAN_TRIANGLE_AFFINE_COEFFICIENT_LIMIT;
+}
+
+static int32_t
+milan_divide_affine_coefficient (int64_t numerator,
+ int64_t denominator,
+ int64_t half_denominator)
+{
+ uint64_t dividend_bits;
+ int64_t dividend;
+ int64_t quotient;
+
+ if (denominator == 0)
+ return 0;
+ /* Native rounds with wrapping qword arithmetic before signed division. The
+ * rounded dividend can be negative even with a positive Gram determinant. */
+ dividend_bits = numerator < 0 ?
+ (uint64_t) half_denominator - (uint64_t) numerator :
+ (uint64_t) numerator + (uint64_t) half_denominator;
+ memcpy (÷nd, ÷nd_bits, sizeof (dividend));
+ /* INT64_MIN / -1 traps on x86; wrap it like the rest of this arithmetic. */
+ quotient = denominator == -1 ? (int64_t) (UINT64_C (0) - dividend_bits) :
+ dividend / denominator;
+ return milan_reinterpret_uint32_as_int32 (
+ numerator < 0 ? UINT32_C (0) - (uint32_t) quotient :
+ (uint32_t) quotient);
+}
+
+static int64_t
+milan_wrapped_multiply (int64_t first, int64_t second)
+{
+ uint64_t result = (uint64_t) first * (uint64_t) second;
+ int64_t signed_result;
+
+ memcpy (&signed_result, &result, sizeof(signed_result));
+ return signed_result;
+}
+
+static int64_t
+milan_wrapped_add (int64_t first, int64_t second)
+{
+ uint64_t result = (uint64_t) first + (uint64_t) second;
+ int64_t signed_result;
+
+ memcpy (&signed_result, &result, sizeof(signed_result));
+ return signed_result;
+}
+
+static int64_t
+milan_wrapped_subtract (int64_t first, int64_t second)
+{
+ uint64_t result = (uint64_t) first - (uint64_t) second;
+ int64_t signed_result;
+
+ memcpy (&signed_result, &result, sizeof(signed_result));
+ return signed_result;
+}
+
+static void
+milan_refine_affine_least_squares (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ const GoodixMilanFeatureRecord *probe_records,
+ const int32_t *pairs,
+ size_t pair_count,
+ const uint8_t *inliers,
+ int32_t previous_residual,
+ int32_t affine[6])
+{
+ int64_t matrix[3][3] = { { 0 } };
+ int64_t right[3][2] = { { 0 } };
+ size_t inlier_count = 0;
+ int32_t refined[6];
+
+ for (size_t i = 0; i < pair_count; i++)
+ {
+ if (!inliers[i])
+ continue;
+ int32_t enrolled_index = pairs[i * 2];
+ int32_t probe_index = pairs[i * 2 + 1];
+ int64_t source[3] = {
+ (uint16_t) probe_records[probe_index].refined_x,
+ (uint16_t) probe_records[probe_index].refined_y,
+ MILAN_AFFINE_Q8_ONE,
+ };
+ int64_t target[2] = {
+ (uint16_t) enrolled_records[enrolled_index].refined_x,
+ (uint16_t) enrolled_records[enrolled_index].refined_y,
+ };
+
+ for (size_t row = 0; row < 3; row++)
+ {
+ for (size_t column = 0; column < 3; column++)
+ matrix[row][column] += source[row] * source[column];
+ for (size_t column = 0; column < 2; column++)
+ right[row][column] += source[row] * target[column];
+ }
+ inlier_count++;
+ }
+ if (inlier_count < 3)
+ return;
+ for (size_t row = 0; row < 3; row++)
+ {
+ for (size_t column = 0; column < 3; column++)
+ matrix[row][column] =
+ (matrix[row][column] + MILAN_AFFINE_Q8_HALF) >>
+ MILAN_AFFINE_Q8_SHIFT;
+ for (size_t column = 0; column < 2; column++)
+ right[row][column] =
+ (right[row][column] + MILAN_AFFINE_Q8_HALF) >>
+ MILAN_AFFINE_Q8_SHIFT;
+ }
+
+ int64_t cofactors[3][3] = {
+ {
+ milan_wrapped_subtract (
+ milan_wrapped_multiply (matrix[1][1], matrix[2][2]),
+ milan_wrapped_multiply (matrix[1][2], matrix[2][1])),
+ milan_wrapped_subtract (
+ milan_wrapped_multiply (matrix[0][2], matrix[2][1]),
+ milan_wrapped_multiply (matrix[0][1], matrix[2][2])),
+ milan_wrapped_subtract (
+ milan_wrapped_multiply (matrix[0][1], matrix[1][2]),
+ milan_wrapped_multiply (matrix[0][2], matrix[1][1])),
+ },
+ {
+ milan_wrapped_subtract (
+ milan_wrapped_multiply (matrix[2][0], matrix[1][2]),
+ milan_wrapped_multiply (matrix[1][0], matrix[2][2])),
+ milan_wrapped_subtract (
+ milan_wrapped_multiply (matrix[0][0], matrix[2][2]),
+ milan_wrapped_multiply (matrix[2][0], matrix[0][2])),
+ milan_wrapped_subtract (
+ milan_wrapped_multiply (matrix[1][0], matrix[0][2]),
+ milan_wrapped_multiply (matrix[0][0], matrix[1][2])),
+ },
+ {
+ milan_wrapped_subtract (
+ milan_wrapped_multiply (matrix[1][0], matrix[2][1]),
+ milan_wrapped_multiply (matrix[2][0], matrix[1][1])),
+ milan_wrapped_subtract (
+ milan_wrapped_multiply (matrix[2][0], matrix[0][1]),
+ milan_wrapped_multiply (matrix[0][0], matrix[2][1])),
+ milan_wrapped_subtract (
+ milan_wrapped_multiply (matrix[0][0], matrix[1][1]),
+ milan_wrapped_multiply (matrix[1][0], matrix[0][1])),
+ },
+ };
+ int64_t determinant = milan_wrapped_add (
+ milan_wrapped_add (
+ milan_wrapped_multiply (matrix[0][0], cofactors[0][0]),
+ milan_wrapped_multiply (matrix[0][1], cofactors[0][1])),
+ milan_wrapped_multiply (matrix[0][2], cofactors[0][2]));
+ int64_t rounded_determinant = milan_wrapped_add (
+ determinant, MILAN_AFFINE_Q8_HALF);
+ int64_t denominator = rounded_determinant >> MILAN_AFFINE_Q8_SHIFT;
+ int64_t half_denominator = rounded_determinant >> 9;
+
+ if (denominator == 0)
+ return;
+ for (size_t output = 0; output < 2; output++)
+ {
+ int64_t numerator[3];
+
+ for (size_t row = 0; row < 3; row++)
+ numerator[row] = milan_wrapped_add (
+ milan_wrapped_add (
+ milan_wrapped_multiply (right[0][output], cofactors[row][0]),
+ milan_wrapped_multiply (right[1][output], cofactors[row][1])),
+ milan_wrapped_multiply (right[2][output], cofactors[row][2]));
+
+ refined[output * 3] = milan_divide_affine_coefficient (
+ numerator[0], denominator, half_denominator);
+ refined[output * 3 + 1] = milan_divide_affine_coefficient (
+ numerator[1], denominator, half_denominator);
+ refined[output * 3 + 2] = milan_divide_affine_coefficient (
+ numerator[2], denominator, half_denominator);
+ }
+
+ size_t refined_inlier_count = 0;
+ uint64_t refined_residual_sum = 0;
+
+ for (size_t i = 0; i < pair_count; i++)
+ {
+ int32_t enrolled_index = pairs[i * 2];
+ int32_t probe_index = pairs[i * 2 + 1];
+ int32_t x = (uint16_t) probe_records[probe_index].refined_x;
+ int32_t y = (uint16_t) probe_records[probe_index].refined_y;
+ int64_t transformed_x =
+ (((int64_t) refined[0] * x + (int64_t) refined[1] * y +
+ MILAN_AFFINE_Q8_HALF) >> MILAN_AFFINE_Q8_SHIFT) +
+ refined[2];
+ int64_t transformed_y =
+ (((int64_t) refined[3] * x + (int64_t) refined[4] * y +
+ MILAN_AFFINE_Q8_HALF) >> MILAN_AFFINE_Q8_SHIFT) +
+ refined[5];
+ /* Refinement can publish large coefficients after orientation filtering.
+ * Native narrows the residual to a signed dword before squaring it. */
+ int64_t dx = milan_reinterpret_uint32_as_int32 (
+ (uint32_t) transformed_x -
+ (uint16_t) enrolled_records[enrolled_index].refined_x);
+ int64_t dy = milan_reinterpret_uint32_as_int32 (
+ (uint32_t) transformed_y -
+ (uint16_t) enrolled_records[enrolled_index].refined_y);
+ uint64_t squared = (uint64_t) (dx * dx) + (uint64_t) (dy * dy);
+
+ if (squared < MILAN_RECOGNITION_INLIER_SQUARED_LIMIT)
+ {
+ refined_inlier_count++;
+ refined_residual_sum += squared;
+ }
+ }
+ int32_t refined_residual = refined_inlier_count == 0
+ ? MILAN_RECOGNITION_NO_MODEL_RESIDUAL
+ : (int32_t) ((refined_residual_sum +
+ (refined_inlier_count >> 1)) /
+ refined_inlier_count);
+
+ if (refined_residual < previous_residual &&
+ refined_inlier_count >= inlier_count)
+ memcpy (affine, refined, sizeof(refined));
+}
+
+static uint64_t milan_match_integer_sqrt_u64 (uint64_t value);
+
+static int
+milan_filter_affine_orientation (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ const GoodixMilanFeatureRecord *probe_records,
+ const int32_t *pairs,
+ size_t pair_count,
+ const int32_t affine[6],
+ uint8_t inliers[MILAN_MATCH_MAX_PAIRS])
+{
+ uint32_t first_length = (uint32_t) milan_match_integer_sqrt_u64 (
+ (uint64_t) ((int64_t) affine[0] * affine[0]) +
+ (uint64_t) ((int64_t) affine[3] * affine[3]));
+ uint32_t second_length = (uint32_t) milan_match_integer_sqrt_u64 (
+ (uint64_t) ((int64_t) affine[1] * affine[1]) +
+ (uint64_t) ((int64_t) affine[4] * affine[4]));
+ int32_t average_length = (int32_t) ((first_length + second_length) / 2);
+ int retained = 0;
+
+ if (average_length == 0)
+ return 0;
+
+ int32_t cosine = ((affine[4] + affine[0]) / 2 * MILAN_AFFINE_Q8_ONE) /
+ average_length;
+ int32_t sine = ((affine[3] - affine[1]) / 2 * MILAN_AFFINE_Q8_ONE) /
+ average_length;
+ int32_t affine_angle = feature_atan2 (cosine, sine);
+
+ if (affine_angle < 0)
+ affine_angle += MILAN_ORIENTATION_FULL_PERIOD;
+ for (size_t i = 0; i < pair_count; i++)
+ {
+ if (inliers[i])
+ {
+ int32_t enrolled_index = pairs[i * 2];
+ int32_t probe_index = pairs[i * 2 + 1];
+ int32_t difference =
+ enrolled_records[enrolled_index].orientation -
+ probe_records[probe_index].orientation + affine_angle;
+ int32_t direct = difference;
+ int32_t opposite = difference + MILAN_ORIENTATION_PERIOD;
+
+ if (direct < 0)
+ direct += MILAN_ORIENTATION_FULL_PERIOD;
+ if (direct > MILAN_ORIENTATION_FULL_PERIOD)
+ direct -= MILAN_ORIENTATION_FULL_PERIOD;
+ if (MILAN_ORIENTATION_FULL_PERIOD - direct < direct)
+ direct = MILAN_ORIENTATION_FULL_PERIOD - direct;
+ if (opposite < 0)
+ opposite += MILAN_ORIENTATION_FULL_PERIOD;
+ if (opposite > MILAN_ORIENTATION_FULL_PERIOD)
+ opposite -= MILAN_ORIENTATION_FULL_PERIOD;
+ if (MILAN_ORIENTATION_FULL_PERIOD - opposite < opposite)
+ opposite = MILAN_ORIENTATION_FULL_PERIOD - opposite;
+ if (opposite < direct)
+ direct = opposite;
+ if (direct > MILAN_RECOGNITION_ORIENTATION_LIMIT)
+ inliers[i] = 0;
+ }
+ retained += inliers[i] != 0;
+ }
+ return retained;
+}
+
+int
+goodix_milan_filter_recognition_pairs_internal (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ const GoodixMilanFeatureRecord *probe_records,
+ const int32_t *pairs,
+ size_t match_count,
+ int32_t best_affine[6],
+ int *best_residual,
+ uint8_t *output_mask,
+ int *model_valid)
+{
+ int best_inliers = 0;
+ uint8_t best_mask[MILAN_MATCH_MAX_PAIRS] = { 0 };
+ int triangle_count = 0;
+
+ if (model_valid)
+ *model_valid = 0;
+ *best_residual = MILAN_RECOGNITION_NO_MODEL_RESIDUAL;
+ memset (best_affine, 0, 6 * sizeof(*best_affine));
+ for (size_t first = 0; first + 2 < match_count; first++)
+ {
+ if (triangle_count >= MILAN_RECOGNITION_TRIANGLE_LIMIT)
+ break;
+ for (size_t second = first + 1; second + 1 < match_count; second++)
+ {
+ const size_t edge[2] = { first, second };
+ int32_t source[6];
+ int32_t target[6];
+ int32_t edge_orientations[2];
+
+ for (size_t i = 0; i < 2; i++)
+ {
+ int32_t enrolled_index = pairs[edge[i] * 2];
+ int32_t probe_index = pairs[edge[i] * 2 + 1];
+
+ source[i * 2] =
+ (uint16_t) probe_records[probe_index].refined_x;
+ source[i * 2 + 1] =
+ (uint16_t) probe_records[probe_index].refined_y;
+ target[i * 2] =
+ (uint16_t) enrolled_records[enrolled_index].refined_x;
+ target[i * 2 + 1] =
+ (uint16_t) enrolled_records[enrolled_index].refined_y;
+ edge_orientations[i] = milan_normalize_orientation_difference (
+ enrolled_records[enrolled_index].orientation -
+ probe_records[probe_index].orientation,
+ MILAN_ORIENTATION_HALF_PERIOD, MILAN_ORIENTATION_PERIOD);
+ }
+ if (!milan_triangle_edge_is_consistent (
+ milan_triangle_distance_shift_then_add (
+ source[0], source[1], source[2], source[3]),
+ milan_triangle_distance_shift_then_add (
+ target[0], target[1], target[2], target[3])))
+ continue;
+ for (size_t third = second + 1; third < match_count; third++)
+ {
+ /* The orientation retry mutates its per-triangle scratch. */
+ int32_t orientation_differences[3] = {
+ edge_orientations[0], edge_orientations[1], 0
+ };
+ int32_t affine[6];
+ int inliers = 0;
+ int64_t residual_sum = 0;
+ uint8_t mask[MILAN_MATCH_MAX_PAIRS] = { 0 };
+
+ {
+ int32_t enrolled_index = pairs[third * 2];
+ int32_t probe_index = pairs[third * 2 + 1];
+
+ source[4] = (uint16_t) probe_records[probe_index].refined_x;
+ source[5] = (uint16_t) probe_records[probe_index].refined_y;
+ target[4] = (uint16_t) enrolled_records[enrolled_index].refined_x;
+ target[5] = (uint16_t) enrolled_records[enrolled_index].refined_y;
+ orientation_differences[2] =
+ milan_normalize_orientation_difference (
+ enrolled_records[enrolled_index].orientation -
+ probe_records[probe_index].orientation,
+ MILAN_ORIENTATION_HALF_PERIOD, MILAN_ORIENTATION_PERIOD);
+ }
+ if (!milan_triangle_edge_is_consistent (
+ milan_triangle_distance_shift_then_add (
+ source[0], source[1], source[4], source[5]),
+ milan_triangle_distance_shift_then_add (
+ target[0], target[1], target[4], target[5])) ||
+ !milan_triangle_edge_is_consistent (
+ milan_triangle_distance_add_then_shift (
+ source[2], source[3], source[4], source[5]),
+ milan_triangle_distance_add_then_shift (
+ target[2], target[3], target[4], target[5])) ||
+ !milan_triangle_orientations_are_consistent (
+ orientation_differences))
+ continue;
+ triangle_count++;
+ milan_affine_from_three_points (source, target, affine);
+ if (!milan_triangle_affine_is_consistent (affine))
+ continue;
+ for (size_t i = 0; i < match_count; i++)
+ {
+ int32_t enrolled_index = pairs[i * 2];
+ int32_t probe_index = pairs[i * 2 + 1];
+ int32_t x = (uint16_t) probe_records[probe_index].refined_x;
+ int32_t y = (uint16_t) probe_records[probe_index].refined_y;
+ int64_t transformed_x =
+ (((int64_t) affine[0] * x +
+ (int64_t) affine[1] * y + 0x80) >> 8) + affine[2];
+ int64_t transformed_y =
+ (((int64_t) affine[3] * x +
+ (int64_t) affine[4] * y + 0x80) >> 8) + affine[5];
+ int64_t dx = transformed_x -
+ (uint16_t) enrolled_records[enrolled_index].refined_x;
+ int64_t dy = transformed_y -
+ (uint16_t) enrolled_records[enrolled_index].refined_y;
+ int64_t squared = dx * dx + dy * dy;
+
+ if (llabs (dx) < MILAN_RECOGNITION_INLIER_AXIS_LIMIT &&
+ llabs (dy) < MILAN_RECOGNITION_INLIER_AXIS_LIMIT &&
+ squared < MILAN_RECOGNITION_INLIER_SQUARED_LIMIT)
+ {
+ inliers++;
+ residual_sum += squared;
+ mask[i] = 1;
+ }
+ }
+ int residual = inliers == 0
+ ? MILAN_RECOGNITION_NO_MODEL_RESIDUAL
+ : (int) ((residual_sum + (inliers >> 1)) /
+ inliers);
+ if ((inliers > best_inliers ||
+ (inliers == best_inliers && residual < *best_residual)) &&
+ milan_affine_is_valid (affine))
+ {
+ best_inliers = inliers;
+ *best_residual = residual;
+ memcpy (best_affine, affine, 6 * sizeof(*best_affine));
+ memcpy (best_mask, mask, sizeof(best_mask));
+ }
+ if (best_inliers > MILAN_RECOGNITION_EARLY_INLIER_COUNT)
+ goto done;
+ }
+ }
+ }
+done:
+ if (model_valid)
+ *model_valid = best_inliers > 0;
+ best_inliers = milan_filter_affine_orientation (
+ enrolled_records, probe_records, pairs, match_count, best_affine,
+ best_mask);
+ if (output_mask)
+ memcpy (output_mask, best_mask, sizeof(best_mask));
+ if (best_inliers > MILAN_RECOGNITION_REFINE_INLIER_COUNT &&
+ *best_residual > MILAN_RECOGNITION_REFINE_RESIDUAL)
+ milan_refine_affine_least_squares (
+ enrolled_records, probe_records, pairs, match_count, best_mask,
+ *best_residual, best_affine);
+ return best_inliers;
+}
+
+void
+goodix_milan_match_record_metrics_internal (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ const int32_t transform[6],
+ int filtered_count,
+ int32_t *topology_percent,
+ int32_t *geometric_percent,
+ int32_t *topology_bonus,
+ int32_t *topology_distance_output,
+ int32_t *valid_count_output,
+ int32_t *matched_count_output)
+{
+ int valid_topology_records = 0;
+ int matched_topology_records = 0;
+ int topology_distance_sum = 0;
+
+ for (size_t probe_index = 0; probe_index < probe_record_count; probe_index++)
+ {
+ int64_t raw_x =
+ (int64_t) transform[0] * (uint16_t) probe_records[probe_index].refined_x +
+ (int64_t) transform[1] * (uint16_t) probe_records[probe_index].refined_y +
+ (int64_t) transform[2] * 0x100;
+ int64_t raw_y =
+ (int64_t) transform[3] * (uint16_t) probe_records[probe_index].refined_x +
+ (int64_t) transform[4] * (uint16_t) probe_records[probe_index].refined_y +
+ (int64_t) transform[5] * 0x100;
+ int32_t transformed_x = milan_reinterpret_uint32_as_int32 (
+ raw_x < 1 ? UINT32_C (0) - (uint32_t) ((0x80 - raw_x) >> 8) :
+ (uint32_t) ((raw_x + 0x80) >> 8));
+ int32_t transformed_y = milan_reinterpret_uint32_as_int32 (
+ raw_y < 1 ? UINT32_C (0) - (uint32_t) ((0x80 - raw_y) >> 8) :
+ (uint32_t) ((raw_y + 0x80) >> 8));
+
+ if (transformed_x < 0x600 ||
+ transformed_x >=
+ (GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS - 7) * 0x100 ||
+ transformed_y < 0x600 ||
+ transformed_y >=
+ (GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS - 7) * 0x100)
+ continue;
+ valid_topology_records++;
+
+ int best_index = -1;
+ int best_squared = INT32_MAX;
+ for (size_t enrolled_index = 0;
+ enrolled_index < enrolled_record_count; enrolled_index++)
+ {
+ if ((enrolled_records[enrolled_index].foreground & 3) !=
+ (probe_records[probe_index].foreground & 3))
+ continue;
+ int32_t dx = transformed_x -
+ (uint16_t) enrolled_records[enrolled_index].refined_x;
+ int32_t dy = transformed_y -
+ (uint16_t) enrolled_records[enrolled_index].refined_y;
+ if (abs (dx) > 0x200 || abs (dy) > 0x200)
+ continue;
+ int squared = dx * dx + dy * dy;
+ if (squared < best_squared)
+ {
+ best_squared = squared;
+ best_index = (int) enrolled_index;
+ }
+ }
+ if (best_index >= 0 && best_squared < 0x40000)
+ {
+ const uint8_t *enrolled =
+ (const uint8_t *) &enrolled_records[best_index];
+ const uint8_t *probe = (const uint8_t *) &probe_records[probe_index];
+ int first_distance = 0;
+ int second_distance = 0;
+
+ for (size_t i = 0; i < 8; i++)
+ {
+ first_distance += __builtin_popcount (
+ (unsigned) (enrolled[40 + i] ^ probe[40 + i]));
+ second_distance += __builtin_popcount (
+ (unsigned) (enrolled[40 + i] ^ probe[48 + i]));
+ }
+ matched_topology_records++;
+ topology_distance_sum += first_distance < second_distance
+ ? first_distance
+ : second_distance;
+ }
+ }
+
+ int topology_distance = matched_topology_records == 0
+ ? 0
+ : topology_distance_sum /
+ matched_topology_records;
+
+ *topology_percent = valid_topology_records == 0
+ ? 0
+ : matched_topology_records * 100 /
+ valid_topology_records;
+ *geometric_percent = valid_topology_records == 0
+ ? 0
+ : filtered_count * 100 / valid_topology_records;
+ *topology_bonus = *topology_percent > 30 && topology_distance < 10 &&
+ filtered_count < 31;
+ if (topology_distance_output)
+ *topology_distance_output = topology_distance;
+ if (valid_count_output)
+ *valid_count_output = valid_topology_records;
+ if (matched_count_output)
+ *matched_count_output = matched_topology_records;
+}
+
+static uint64_t
+milan_match_integer_sqrt_u64 (uint64_t value)
+{
+ uint64_t root = 0;
+ uint64_t bit = UINT64_C (1) << 62;
+
+ while (bit > value)
+ bit >>= 2;
+ while (bit != 0)
+ {
+ if (value >= root + bit)
+ {
+ value -= root + bit;
+ root = (root >> 1) + bit;
+ }
+ else
+ root >>= 1;
+ bit >>= 2;
+ }
+ return root;
+}
+
+static uint32_t
+milan_match_affine_product_root (uint64_t value)
+{
+ uint32_t root = 0;
+ uint64_t bit = UINT64_C (0x80000000);
+
+ /* Native doubles the root in a dword before widening the trial. */
+ for (int shift = 31; shift >= 0; shift--, bit >>= 1)
+ {
+ uint64_t trial = ((uint32_t) (root * UINT32_C (2)) + bit) << shift;
+
+ if (value >= trial)
+ {
+ root += (uint32_t) bit;
+ value -= trial;
+ }
+ }
+ return root;
+}
+
+void
+goodix_milan_match_affine_penalties (const int32_t transform[6],
+ int32_t *scale_penalty,
+ int32_t *orthogonality_penalty,
+ int32_t *strong_orthogonality_penalty)
+{
+ int32_t average_scale;
+ int32_t orthogonality;
+
+ goodix_milan_match_affine_details (transform, &average_scale, &orthogonality);
+ *scale_penalty = (uint32_t) (average_scale - 234) > 47;
+ *orthogonality_penalty = orthogonality >= 0x147b;
+ if (strong_orthogonality_penalty)
+ *strong_orthogonality_penalty = orthogonality >= 0x28f6;
+}
+
+void
+goodix_milan_match_affine_details (const int32_t transform[6],
+ int32_t *average_scale,
+ int32_t *absolute_dot_q16)
+{
+ uint32_t a = (uint32_t) transform[0];
+ uint32_t b = (uint32_t) transform[1];
+ uint32_t c = (uint32_t) transform[3];
+ uint32_t d = (uint32_t) transform[4];
+ uint32_t first_squared = a * a + c * c;
+ uint32_t second_squared = b * b + d * d;
+ uint32_t first_length = (uint32_t) milan_match_integer_sqrt_u64 (first_squared);
+ uint32_t second_length = (uint32_t) milan_match_integer_sqrt_u64 (second_squared);
+ int64_t product =
+ (int64_t) milan_reinterpret_uint32_as_int32 (first_squared) *
+ milan_reinterpret_uint32_as_int32 (second_squared);
+ uint32_t product_length = milan_match_affine_product_root ((uint64_t) product);
+ int64_t dot = milan_reinterpret_uint32_as_int32 (a * b + c * d);
+
+ *average_scale = (int32_t) ((first_length + second_length) >> 1);
+ *absolute_dot_q16 = 0;
+ if (first_length != 0 && product_length != 0)
+ *absolute_dot_q16 = milan_reinterpret_uint32_as_int32 (
+ (uint32_t) ((dot * 0x10000) / product_length));
+ if (*absolute_dot_q16 < 0)
+ *absolute_dot_q16 = milan_reinterpret_uint32_as_int32 (
+ UINT32_C (0) - (uint32_t) *absolute_dot_q16);
+}
+
+void
+goodix_milan_match_fit_affine_state (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ const GoodixMilanFeatureRecord *probe_records,
+ const int32_t *pairs,
+ size_t pair_count,
+ int attempted,
+ MilanMatchAffineState *state)
+{
+ memset (state, 0, sizeof(*state));
+ state->selected_pair_count = pair_count;
+ state->attempted = attempted && pair_count >= 3;
+ if (!state->attempted)
+ return;
+
+ state->filtered_count = goodix_milan_filter_recognition_pairs_internal (
+ enrolled_records, probe_records, pairs, pair_count, state->affine,
+ &state->residual, NULL, &state->valid);
+}
+
+int
+goodix_milan_filter_recognition_pairs (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ const GoodixMilanFeatureRecord *probe_records,
+ const int32_t *pairs,
+ size_t pair_count,
+ int32_t transform[6],
+ size_t *filtered_count,
+ int32_t *residual)
+{
+ int32_t best_residual = 0x190000;
+ int count;
+
+ if (!enrolled_records || !probe_records || !pairs ||
+ pair_count > MILAN_MATCH_MAX_PAIRS ||
+ !transform || !filtered_count || !residual)
+ return -1;
+ count = goodix_milan_filter_recognition_pairs_internal (
+ enrolled_records, probe_records, pairs, pair_count, transform,
+ &best_residual, NULL, NULL);
+ *filtered_count = (size_t) count;
+ *residual = best_residual;
+ return count > 0 ? 0 : -1;
+}
+
+int
+goodix_milan_estimate_relation (
+ const GoodixMilanFeatureRecord *prior_records,
+ size_t prior_record_count,
+ const GoodixMilanFeatureRecord *current_records,
+ size_t current_record_count,
+ int32_t relation_index,
+ GoodixMilanTemplateRelation *relation)
+{
+ MilanFeatureMatch matches[31];
+ int32_t best_affine[6] = { 0 };
+ int best_inliers = 0;
+ int best_residual = 0x190000;
+ size_t match_count;
+
+ if (!prior_records || !current_records || !relation ||
+ prior_record_count == 0 || current_record_count == 0 ||
+ prior_record_count > 150 || current_record_count > 150)
+ return -1;
+ match_count = goodix_milan_match_feature_records (
+ prior_records, prior_record_count, current_records, current_record_count,
+ matches);
+ if (match_count < 5)
+ return -1;
+
+ for (size_t first = 0; first + 2 < match_count; first++)
+ for (size_t second = first + 1; second + 1 < match_count; second++)
+ for (size_t third = second + 1; third < match_count; third++)
+ {
+ const size_t selected[3] = { first, second, third };
+ int32_t source[6];
+ int32_t target[6];
+ int32_t affine[6];
+ int inliers = 0;
+ int64_t residual_sum = 0;
+
+ for (size_t i = 0; i < 3; i++)
+ {
+ const MilanFeatureMatch *match = &matches[selected[i]];
+
+ source[i * 2] = (uint16_t)
+ current_records[match->current_index].refined_x;
+ source[i * 2 + 1] = (uint16_t)
+ current_records[match->current_index].refined_y;
+ target[i * 2] = (uint16_t)
+ prior_records[match->prior_index].refined_x;
+ target[i * 2 + 1] = (uint16_t)
+ prior_records[match->prior_index].refined_y;
+ }
+ milan_affine_from_three_points (source, target, affine);
+ for (size_t i = 0; i < match_count; i++)
+ {
+ int32_t x = (uint16_t)
+ current_records[matches[i].current_index].refined_x;
+ int32_t y = (uint16_t)
+ current_records[matches[i].current_index].refined_y;
+ int64_t transformed_x =
+ (((int64_t) affine[0] * x +
+ (int64_t) affine[1] * y) >> 8) +
+ affine[2];
+ int64_t transformed_y =
+ (((int64_t) affine[3] * x +
+ (int64_t) affine[4] * y) >> 8) +
+ affine[5];
+ /* Native rejects mapped coordinates before subtraction, then
+ * bounds each residual before evaluating its square. */
+ if (transformed_x <= -INT64_C(0x100000000) ||
+ transformed_x >= INT64_C(0x100000000) ||
+ transformed_y <= -INT64_C(0x100000000) ||
+ transformed_y >= INT64_C(0x100000000))
+ continue;
+ int64_t dx = transformed_x -
+ (uint16_t) prior_records[matches[i].prior_index].refined_x;
+ int64_t dy = transformed_y -
+ (uint16_t) prior_records[matches[i].prior_index].refined_y;
+ if (dx < -640 || dx > 640 || dy < -640 || dy > 640)
+ continue;
+ int64_t squared = dx * dx + dy * dy;
+
+ if (squared < 0x64000)
+ {
+ inliers++;
+ residual_sum += squared;
+ }
+ }
+ int residual = inliers == 0
+ ? 0x190000
+ : (int) ((residual_sum + (inliers >> 1)) / inliers);
+ if ((inliers > best_inliers ||
+ (inliers == best_inliers && residual < best_residual)) &&
+ milan_affine_is_valid (affine))
+ {
+ best_inliers = inliers;
+ best_residual = residual;
+ memcpy (best_affine, affine, sizeof(best_affine));
+ }
+ if (best_inliers > 20)
+ goto done;
+ }
+
+done:
+ if (best_inliers == 0)
+ return -1;
+ relation->index = relation_index;
+ relation->values[0] = best_inliers;
+ memcpy (relation->values + 1, best_affine, sizeof(best_affine));
+ return 0;
+}
+
+static void
+milan_fill_record_index_map (const GoodixMilanFeatureRecord *records,
+ size_t begin,
+ size_t end,
+ int32_t radius,
+ int16_t map[GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS])
+{
+ memset (map, 0xff,
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS * sizeof (*map));
+ for (size_t index = begin; index < end; index++)
+ {
+ int32_t x = ((uint16_t) records[index].refined_x + 0x80) >> 8;
+ int32_t y = ((uint16_t) records[index].refined_y + 0x80) >> 8;
+ int32_t left = x > radius ? x - radius : 0;
+ int32_t right = x + radius < GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS ?
+ x + radius :
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS - 1;
+ int32_t top = y > radius ? y - radius : 0;
+ int32_t bottom = y + radius < GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS ?
+ y + radius :
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS - 1;
+
+ for (int32_t row = top; row <= bottom; row++)
+ for (int32_t column = left; column <= right; column++)
+ map[row * GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS + column] =
+ (int16_t) index;
+ }
+}
+
+int
+goodix_milan_refine_record_similarity (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ size_t enrolled_partition,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ size_t probe_partition,
+ const int32_t transform[6],
+ int32_t search_radius,
+ int32_t refined[6])
+{
+ int32_t inverse[6];
+ int32_t pairs[300];
+ int16_t index_map[GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS];
+ size_t pair_count = 0;
+ uint64_t source_x_sum = 0;
+ uint64_t source_y_sum = 0;
+ uint64_t target_x_sum = 0;
+ uint64_t target_y_sum = 0;
+ uint64_t source_square_sum = 0;
+ int64_t dot_sum = 0;
+ int64_t cross_sum = 0;
+
+ if (enrolled_partition > enrolled_record_count ||
+ probe_partition > probe_record_count || search_radius < 0 ||
+ goodix_milan_transform_invert (transform, inverse) != 0)
+ return -1;
+ for (size_t partition = 0; partition < 2; partition++)
+ {
+ size_t enrolled_begin = partition == 0 ? 0 : enrolled_partition;
+ size_t enrolled_end = partition == 0 ? enrolled_partition
+ : enrolled_record_count;
+ size_t probe_begin = partition == 0 ? 0 : probe_partition;
+ size_t probe_end = partition == 0 ? probe_partition : probe_record_count;
+
+ milan_fill_record_index_map (
+ probe_records, probe_begin, probe_end, search_radius, index_map);
+ for (size_t index = enrolled_begin; index < enrolled_end; index++)
+ {
+ int32_t x = (uint16_t) enrolled_records[index].refined_x;
+ int32_t y = (uint16_t) enrolled_records[index].refined_y;
+ int64_t mapped_x =
+ (((int64_t) inverse[0] * x + (int64_t) inverse[1] * y + 0x80) >> 8) +
+ inverse[2];
+ int64_t mapped_y =
+ (((int64_t) inverse[3] * x + (int64_t) inverse[4] * y + 0x80) >> 8) +
+ inverse[5];
+ /* Native rounds the translated coordinate as a wrapping dword. */
+ int32_t pixel_x = milan_reinterpret_uint32_as_int32 (
+ (uint32_t) mapped_x + UINT32_C (0x80)) >> 8;
+ int32_t pixel_y = milan_reinterpret_uint32_as_int32 (
+ (uint32_t) mapped_y + UINT32_C (0x80)) >> 8;
+
+ if (pixel_x < 0 ||
+ pixel_x >= GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS ||
+ pixel_y < 0 ||
+ pixel_y >= GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS)
+ continue;
+ int32_t probe_index =
+ index_map[pixel_y * GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS +
+ pixel_x];
+ if (probe_index < 0 || pair_count == 150)
+ continue;
+ pairs[pair_count * 2] = (int32_t) index;
+ pairs[pair_count * 2 + 1] = probe_index;
+ pair_count++;
+ }
+ }
+ if (pair_count < 3)
+ return -1;
+ for (size_t pair = 0; pair < pair_count; pair++)
+ {
+ int32_t enrolled_index = pairs[pair * 2];
+ int32_t probe_index = pairs[pair * 2 + 1];
+ uint32_t source_x = (uint16_t) probe_records[probe_index].refined_x;
+ uint32_t source_y = (uint16_t) probe_records[probe_index].refined_y;
+ uint32_t target_x =
+ (uint16_t) enrolled_records[enrolled_index].refined_x;
+ uint32_t target_y =
+ (uint16_t) enrolled_records[enrolled_index].refined_y;
+
+ source_x_sum += source_x;
+ source_y_sum += source_y;
+ target_x_sum += target_x;
+ target_y_sum += target_y;
+ source_square_sum +=
+ (uint64_t) source_x * source_x + (uint64_t) source_y * source_y;
+ dot_sum += (int64_t) target_x * source_x +
+ (int64_t) target_y * source_y;
+ cross_sum += (int64_t) target_x * -(int64_t) source_y +
+ (int64_t) target_y * source_x;
+ }
+
+ int64_t count = (int64_t) pair_count;
+ int64_t source_x = (int64_t) (source_x_sum + 0x80) >> 8;
+ int64_t source_y = (int64_t) (source_y_sum + 0x80) >> 8;
+ int64_t target_x = (int64_t) (target_x_sum + 0x80) >> 8;
+ int64_t target_y = (int64_t) (target_y_sum + 0x80) >> 8;
+ int64_t squares = (int64_t) (source_square_sum + 0x8000) >> 16;
+ int64_t dot = (dot_sum + 0x8000) >> 16;
+ int64_t cross = (cross_sum + 0x8000) >> 16;
+ int64_t denominator =
+ squares * count - source_x * source_x - source_y * source_y;
+
+ if (denominator == 0)
+ return -1;
+ int64_t reciprocal = ((denominator >> 1) + INT64_C (0x800000000)) /
+ denominator;
+ /* At most 150 unsigned-word pairs bound the sums and denominator, and
+ * reciprocal * source_x/y fit signed64. Later fit products wrap natively. */
+ int64_t center = milan_wrapped_add (
+ milan_wrapped_multiply (reciprocal,
+ source_x * source_x + source_y * source_y),
+ INT64_C (0x800000000)) / count;
+ int64_t negative_source_x = -(reciprocal * source_x);
+ int64_t negative_source_y = -(reciprocal * source_y);
+
+ refined[0] = milan_reinterpret_uint32_as_int32 ((uint32_t) (
+ milan_wrapped_multiply (count * dot - target_y * source_y -
+ target_x * source_x, reciprocal) >> 27));
+ refined[4] = refined[0];
+ refined[3] = milan_reinterpret_uint32_as_int32 ((uint32_t) (
+ milan_wrapped_multiply (count * cross - target_y * source_x +
+ target_x * source_y, reciprocal) >> 27));
+ refined[1] = milan_reinterpret_uint32_as_int32 (
+ UINT32_C (0) - (uint32_t) refined[3]);
+ refined[5] = milan_reinterpret_uint32_as_int32 ((uint32_t) (
+ milan_wrapped_add (
+ milan_wrapped_add (milan_wrapped_multiply (negative_source_x, cross),
+ milan_wrapped_multiply (negative_source_y, dot)),
+ milan_wrapped_multiply (center, target_y)) >> 27));
+ refined[2] = milan_reinterpret_uint32_as_int32 ((uint32_t) (
+ milan_wrapped_add (
+ milan_wrapped_subtract (milan_wrapped_multiply (negative_source_x, dot),
+ milan_wrapped_multiply (negative_source_y, cross)),
+ milan_wrapped_multiply (center, target_x)) >> 27));
+ return 0;
+}
+
+int
+goodix_milan_match_post_admission_replaces (int32_t current_score,
+ int32_t current_detail,
+ int32_t alternate_score,
+ int32_t alternate_detail)
+{
+ return alternate_score != 0x80 &&
+ (current_score == 0x80 || alternate_detail > current_detail);
+}
diff --git a/libfprint/drivers/goodix53x5/milan/match/geometry.h b/libfprint/drivers/goodix53x5/milan/match/geometry.h
new file mode 100644
index 0000000..8ae8292
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/geometry.h
@@ -0,0 +1,79 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan match geometry internals
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include "milan/milan.h"
+
+typedef struct
+{
+ int32_t affine[6];
+ int32_t residual;
+ int32_t filtered_count;
+ size_t selected_pair_count;
+ int attempted;
+ int valid;
+} MilanMatchAffineState;
+
+int goodix_milan_filter_recognition_pairs_internal (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ const GoodixMilanFeatureRecord *probe_records,
+ const int32_t *pairs,
+ size_t match_count,
+ int32_t best_affine[6],
+ int *best_residual,
+ uint8_t *output_mask,
+ int *model_valid);
+
+void goodix_milan_match_record_metrics_internal (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ const int32_t transform[6],
+ int filtered_count,
+ int32_t *topology_percent,
+ int32_t *geometric_percent,
+ int32_t *topology_bonus,
+ int32_t *topology_distance_output,
+ int32_t *valid_count_output,
+ int32_t *matched_count_output);
+
+void goodix_milan_match_affine_penalties (const int32_t transform[6],
+ int32_t *scale_penalty,
+ int32_t *orthogonality_penalty,
+ int32_t *strong_orthogonality_penalty);
+void goodix_milan_match_affine_details (const int32_t transform[6],
+ int32_t *average_scale,
+ int32_t *absolute_dot_q16);
+
+void goodix_milan_match_fit_affine_state (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ const GoodixMilanFeatureRecord *probe_records,
+ const int32_t *pairs,
+ size_t pair_count,
+ int attempted,
+ MilanMatchAffineState *state);
+
+int goodix_milan_refine_record_similarity (
+ const GoodixMilanFeatureRecord *enrolled_records,
+ size_t enrolled_record_count,
+ size_t enrolled_partition,
+ const GoodixMilanFeatureRecord *probe_records,
+ size_t probe_record_count,
+ size_t probe_partition,
+ const int32_t transform[6],
+ int32_t search_radius,
+ int32_t refined[6]);
+
+int goodix_milan_match_post_admission_replaces (int32_t current_score,
+ int32_t current_detail,
+ int32_t alternate_score,
+ int32_t alternate_detail);
diff --git a/libfprint/drivers/goodix53x5/milan/match/info-private.h b/libfprint/drivers/goodix53x5/milan/match/info-private.h
new file mode 100644
index 0000000..c41768f
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/info-private.h
@@ -0,0 +1,90 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan match info internals
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include "milan/match/match.h"
+#include "milan/match/rescue.h"
+
+typedef struct
+{
+ int quality;
+ int coverage;
+ int32_t optional_c7;
+ GoodixMilanExtractionAuxiliaryState auxiliary;
+} GoodixMilanExtractionMetadata;
+
+typedef struct
+{
+ guint8 high_bitmap[286];
+ guint8 enhanced_bitmap[286];
+ guint8 low_bitmap[286];
+} GoodixMilanFeatureBitmaps;
+
+struct _GoodixMatchInfo
+{
+ GBytes *template;
+ int record_count;
+ int partition_count;
+ GoodixMilanFeatureBitmaps feature_bitmaps;
+ guint8 inline_mask[72];
+ guint8 rescue_mask[GOODIX_MILAN_MATCH_RESCUE_MASK_SIZE];
+ GoodixMilanAntifakeBlob antifake;
+ GoodixMilanFeatureRecord *records;
+ GoodixMilanExtractionMetadata extraction_metadata;
+ /* Live +0x158 output: three summary bytes, or the complete 52x44 plane.
+ * Absent on serialized and native-style queued/study copies. */
+ GBytes *classification;
+};
+
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMilanExtractionMetadata, quality) == 0);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMilanExtractionMetadata, coverage) == 4);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMilanExtractionMetadata, optional_c7) == 8);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMilanExtractionMetadata, auxiliary) == 12);
+G_STATIC_ASSERT (sizeof(GoodixMilanExtractionMetadata) == 16);
+G_STATIC_ASSERT (G_ALIGNOF (GoodixMilanExtractionMetadata) == 4);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMilanFeatureBitmaps, high_bitmap) == 0);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMilanFeatureBitmaps, enhanced_bitmap) == 286);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMilanFeatureBitmaps, low_bitmap) == 572);
+G_STATIC_ASSERT (sizeof(GoodixMilanFeatureBitmaps) == 858);
+G_STATIC_ASSERT (G_ALIGNOF (GoodixMilanFeatureBitmaps) == 1);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, template) == 0);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, record_count) == 8);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, partition_count) == 12);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, feature_bitmaps) == 16);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, feature_bitmaps.high_bitmap) == 16);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, feature_bitmaps.enhanced_bitmap) == 302);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, feature_bitmaps.low_bitmap) == 588);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, inline_mask) == 874);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, rescue_mask) == 946);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, antifake) == 1254);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, records) == 8104);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, extraction_metadata) == 8112);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, extraction_metadata.quality) == 8112);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, extraction_metadata.coverage) == 8116);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, extraction_metadata.optional_c7) == 8120);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, extraction_metadata.auxiliary) == 8124);
+G_STATIC_ASSERT (G_STRUCT_OFFSET (GoodixMatchInfo, classification) == 8128);
+G_STATIC_ASSERT (sizeof(GoodixMatchInfo) == 8136);
+G_STATIC_ASSERT (G_ALIGNOF (GoodixMatchInfo) == 8);
+
+int goodix_milan_match_info_result (
+ const GoodixMatchInfo *probe,
+ const uint8_t *enrolled_template,
+ size_t enrolled_template_size,
+ const GoodixMilanFeatureRecord *const live_records[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ const size_t live_record_counts[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ const size_t live_partition_counts[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY],
+ size_t triggering_index,
+ GoodixMilanMatchResult *match_result
+#ifdef GOODIX53X5_DEBUG
+ , GoodixMilanMatchDiagnostics *diagnostics
+#endif
+ );
diff --git a/libfprint/drivers/goodix53x5/milan/match/info.c b/libfprint/drivers/goodix53x5/milan/match/info.c
new file mode 100644
index 0000000..54a7a05
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/info.c
@@ -0,0 +1,728 @@
+/*
+ * Goodix 53x5 driver for libfprint - native Milan match information
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "milan/debug-hooks.h"
+#include "milan/match/match.h"
+#include "milan/match/info-private.h"
+#include "milan/match/rescue.h"
+#include "milan/milan.h"
+#include "milan/print.h"
+#include "milan/private.h"
+
+#include <string.h>
+
+#define GOODIX_MILAN_OPTIONAL_C7_LEN 5
+#define GOODIX_MILAN_EXTRACTION_COMPONENT_QUEUE_CAPACITY 2450
+
+static void
+goodix_milan_match_pack_rescue_mask (
+ const guint8 dense[GOODIX_MILAN_MATCH_RESCUE_MASK_WIDTH *
+ GOODIX_MILAN_MATCH_RESCUE_MASK_HEIGHT],
+ guint8 packed[GOODIX_MILAN_MATCH_RESCUE_MASK_SIZE])
+{
+ memset (packed, 0, GOODIX_MILAN_MATCH_RESCUE_MASK_SIZE);
+ for (size_t y = 0; y < GOODIX_MILAN_MATCH_RESCUE_MASK_HEIGHT; y++)
+ for (size_t x = 0; x < GOODIX_MILAN_MATCH_RESCUE_MASK_WIDTH; x++)
+ if (dense[y * GOODIX_MILAN_MATCH_RESCUE_MASK_WIDTH + x])
+ packed[y * GOODIX_MILAN_MATCH_RESCUE_MASK_STRIDE + x / 8] |=
+ (guint8) (1U << (x & 7));
+}
+
+static size_t
+goodix_milan_match_record_limit (guint16 sensor_subtype,
+ int coverage,
+ size_t configured_limit)
+{
+ if (sensor_subtype == GOODIX_MILAN_PRINT_SENSOR_TYPE)
+ {
+ size_t limit = (size_t) coverage * configured_limit / 100;
+
+ return limit > 0 ? limit : 1;
+ }
+
+ return ((size_t) coverage * configured_limit + 50) / 100;
+}
+
+static void
+goodix_milan_match_retain_class_components (
+ guint8 mask[GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS],
+ guint maximum_label,
+ guint strict_size_floor,
+ gint *labels,
+ gint *queue)
+{
+ guint component_sizes[72] = { 0 };
+ guint selected_labels[3] = { 0 };
+ guint label_count = 0;
+ guint begin = 0;
+ guint end = 0;
+ guint pending = 0;
+
+ memset (labels, 0xff,
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS * sizeof(*labels));
+ for (guint seed = 0;
+ seed < GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS;
+ seed++)
+ {
+ if (labels[seed] != -1)
+ continue;
+ if (mask[seed] == 0)
+ {
+ labels[seed] = 0;
+ continue;
+ }
+ if (label_count == maximum_label)
+ break;
+ label_count++;
+ labels[seed] = (gint) label_count;
+ component_sizes[label_count]++;
+ queue[end++] = (gint) seed;
+ if (end == GOODIX_MILAN_EXTRACTION_COMPONENT_QUEUE_CAPACITY)
+ end = 0;
+ pending++;
+ while (pending != 0)
+ {
+ gint current = queue[begin++];
+ gint row = current / GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS;
+ gint column = current % GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS;
+ static const gint dx[4] = { -1, 0, 1, 0 };
+ static const gint dy[4] = { 0, -1, 0, 1 };
+
+ if (begin == GOODIX_MILAN_EXTRACTION_COMPONENT_QUEUE_CAPACITY)
+ begin = 0;
+ pending--;
+ for (guint direction = 0; direction < 4; direction++)
+ {
+ gint x = column + dx[direction];
+ gint y = row + dy[direction];
+ gint neighbor;
+
+ if (x < 0 ||
+ x >= GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS ||
+ y < 0 || y >= GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS)
+ continue;
+ neighbor =
+ y * GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS + x;
+ if (labels[neighbor] != -1)
+ continue;
+ if (mask[neighbor] == 0)
+ {
+ labels[neighbor] = 0;
+ continue;
+ }
+ labels[neighbor] = (gint) label_count;
+ component_sizes[label_count]++;
+ /* Native labels/counts discoveries even when enqueue is full. */
+ if (pending < GOODIX_MILAN_EXTRACTION_COMPONENT_QUEUE_CAPACITY)
+ {
+ queue[end++] = neighbor;
+ if (end == GOODIX_MILAN_EXTRACTION_COMPONENT_QUEUE_CAPACITY)
+ end = 0;
+ pending++;
+ }
+ }
+ }
+ }
+
+ for (guint slot = 0; slot < G_N_ELEMENTS (selected_labels); slot++)
+ {
+ guint best_size = strict_size_floor;
+
+ for (guint label = 1; label <= label_count; label++)
+ if (component_sizes[label] > best_size)
+ {
+ selected_labels[slot] = label;
+ best_size = component_sizes[label];
+ }
+ if (selected_labels[slot] != 0)
+ component_sizes[selected_labels[slot]] = 0;
+ }
+
+ for (guint i = 0; i < GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS; i++)
+ mask[i] = (selected_labels[0] != 0 &&
+ labels[i] == (gint) selected_labels[0]) ||
+ (selected_labels[1] != 0 &&
+ labels[i] == (gint) selected_labels[1]) ||
+ (selected_labels[2] != 0 &&
+ labels[i] == (gint) selected_labels[2])
+ ? UINT8_MAX : 0;
+}
+
+static gint32
+goodix_milan_match_update_extraction_classification (
+ GoodixMilanExtractionClassificationState *state,
+ const guint8 classification_source[GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS],
+ const guint8 classification_validity[GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS],
+ guint8 primary_histogram_state,
+ guint8 promoted_secondary_histogram_state,
+ gint coverage,
+ gint32 entry_low_class,
+ gint32 entry_high_class,
+ guint8 *published_class,
+ const guint8 *optional_source,
+ GBytes **published_output)
+{
+ g_autofree guint8 *component_mask = g_malloc (
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS);
+ g_autofree guint8 *current_classes = g_malloc0 (
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS);
+ g_autofree guint8 *stable_classes = g_malloc0 (
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS);
+ g_autofree gint *labels = g_new (gint,
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS);
+ g_autofree gint *queue = g_new (gint,
+ GOODIX_MILAN_EXTRACTION_COMPONENT_QUEUE_CAPACITY);
+ guint stable_class1_count = 0;
+ guint stable_class2_count = 0;
+ gint32 current_class = primary_histogram_state;
+ gint32 high_class;
+ gint32 packed;
+ gboolean append;
+
+ for (guint i = 0; i < GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS; i++)
+ component_mask[i] = classification_source[i] < 0x80 ? UINT8_MAX : 0;
+ goodix_milan_match_retain_class_components (
+ component_mask, 71, 500, labels, queue);
+ for (guint i = 0; i < GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS; i++)
+ if (component_mask[i] != 0)
+ current_classes[i] = 1;
+
+ for (guint i = 0; i < GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS; i++)
+ component_mask[i] = classification_source[i] >= 0x80 &&
+ classification_validity[i] != 0 ? UINT8_MAX : 0;
+ goodix_milan_match_retain_class_components (
+ component_mask, 71, 500, labels, queue);
+ for (guint i = 0; i < GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS; i++)
+ if (component_mask[i] != 0)
+ current_classes[i] = 2;
+
+ if (state->retained_count == 3)
+ {
+ for (guint class_value = 1; class_value <= 2; class_value++)
+ {
+ for (guint i = 0;
+ i < GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS;
+ i++)
+ component_mask[i] =
+ current_classes[i] == class_value &&
+ state->retained_class_planes[0][i] == class_value &&
+ state->retained_class_planes[1][i] == class_value &&
+ state->retained_class_planes[2][i] == class_value ?
+ UINT8_MAX : 0;
+ goodix_milan_match_retain_class_components (
+ component_mask, 31, 350, labels, queue);
+ for (guint i = 0;
+ i < GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS;
+ i++)
+ if (component_mask[i] != 0 && stable_classes[i] == 0)
+ stable_classes[i] = (guint8) class_value;
+ }
+ }
+
+ for (guint i = 0; i < GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS; i++)
+ {
+ stable_class1_count += stable_classes[i] == 1;
+ stable_class2_count += stable_classes[i] == 2;
+ }
+ if (stable_class1_count > 600)
+ {
+ if (current_class <= 2)
+ current_class += 3;
+ }
+ else if (stable_class2_count > 600)
+ {
+ if (current_class == 0)
+ current_class = 3;
+ }
+ else if ((stable_class1_count > 300 || stable_class2_count > 300) &&
+ current_class == 0)
+ current_class = 2;
+
+ high_class = MAX (entry_high_class, current_class);
+ if (high_class < 2 && promoted_secondary_histogram_state > 0)
+ high_class++;
+ if (high_class > 1 || current_class > 1 ||
+ promoted_secondary_histogram_state > 1)
+ {
+ if (state->high_class_hysteresis < 5)
+ state->high_class_hysteresis++;
+ }
+ else if (state->high_class_hysteresis != 0)
+ state->high_class_hysteresis--;
+ if (state->high_class_hysteresis >= 3)
+ high_class = MAX (high_class, 1);
+ packed = high_class * 0x100 + entry_low_class;
+
+ append = coverage >= 75;
+ if (append)
+ {
+ if (state->retained_count < 3)
+ memcpy (state->retained_class_planes[state->retained_count],
+ current_classes,
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS);
+ else
+ {
+ memcpy (state->retained_class_planes[0],
+ state->retained_class_planes[1],
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS);
+ memcpy (state->retained_class_planes[1],
+ state->retained_class_planes[2],
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS);
+ memcpy (state->retained_class_planes[2], current_classes,
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS);
+ }
+ if (state->retained_count < 3)
+ state->retained_count++;
+ }
+ *published_class = (guint8) current_class;
+ guint8 output[52 * 44];
+ gsize output_size = 3;
+
+ if (current_class == 3 || current_class == 4)
+ {
+ for (guint y = 0; y < 44; y++)
+ for (guint x = 0; x < 52; x++)
+ output[y * 52 + x] = stable_classes[y * 2 * 104 + x * 2] ? 2 : 1;
+ output_size = sizeof (output);
+ }
+ else if (current_class == 5)
+ {
+ if (!optional_source)
+ return packed;
+ for (guint y = 0; y < 44; y++)
+ for (guint x = 0; x < 52; x++)
+ output[y * 52 + x] = optional_source[y * 2 * 108 + x * 2];
+ output_size = sizeof (output);
+ }
+ /* The native summary overwrites the first three projected pixels. Ordinary
+ * calls have selector zero. Do not manufacture a mode-5 workspace source. */
+ output[0] = (guint8) current_class;
+ output[1] = 0;
+ output[2] = promoted_secondary_histogram_state;
+ *published_output = g_bytes_new (output, output_size);
+ return packed;
+}
+
+static void
+goodix_milan_match_decode_entry_classes (const guint8 *image,
+ gint32 *packed,
+ gint32 *low_class,
+ gint32 *high_class,
+ guint8 **broken_mask)
+{
+ static const gint32 low_classes[4] = { 0, 2, 2, 3 };
+ static const gint32 high_classes[8] = { 0, 1, 2, 4, 5, 5, 0, 0 };
+ const guint metadata_start = GOODIX_MILAN_SENSOR_COLUMNS - 8;
+ guint32 raw_low;
+ guint32 raw_high;
+
+ *packed = 0;
+ *low_class = 0;
+ *high_class = 0;
+ *broken_mask = NULL;
+ for (guint column = 0; column < metadata_start; column++)
+ if ((image[column] & 1) != (column & 1))
+ return;
+ raw_low = (image[metadata_start] & 1) != 0
+ ? ((image[metadata_start + 1] & 1) != 0 ? 2 : 1)
+ : ((image[metadata_start + 1] & 1) != 0 ? 3 : 0);
+ raw_high = (image[metadata_start + 3] & 1) |
+ ((image[metadata_start + 4] & 1) << 1) |
+ ((image[metadata_start + 5] & 1) << 2);
+ *packed = (gint32) (raw_low + (raw_high << 8));
+ *low_class = low_classes[raw_low];
+ *high_class = high_classes[raw_high];
+ if ((image[metadata_start + 2] & 1) != 0)
+ {
+ *broken_mask = g_malloc (GOODIX_MILAN_SENSOR_PIXELS);
+ memset (*broken_mask, 1, GOODIX_MILAN_SENSOR_COLUMNS);
+ for (guint pixel = GOODIX_MILAN_SENSOR_COLUMNS;
+ pixel < GOODIX_MILAN_SENSOR_PIXELS; pixel++)
+ (*broken_mask)[pixel] = image[pixel] & 1;
+ }
+}
+
+static GoodixMilanExtractionStatus goodix_milan_match_extract_planes (const guint8 *image,
+ const guint8 *primary_contrast_plane,
+ GoodixMilanExtractionClassificationState *classification_state,
+ const GoodixMilanExtractionAuxiliaryState *auxiliary_state,
+ const guint8 *auxiliary_plane,
+ const guint16 *calibration,
+ const guint16 *raw_frame,
+ guint16 t_code,
+ guint16 dac_high,
+ guint16 dac_low,
+ guint16 sensor_subtype,
+ gint32 calibration_scalar,
+ GoodixMatchInfo **result,
+ GoodixMilanExtractionDiagnostics *diagnostics);
+
+GoodixMatchInfo *
+goodix_milan_match_extract_native (const guint8 *image,
+ GoodixMilanPreprocessState *preprocess_state,
+ const guint16 *raw_frame,
+ guint16 t_code,
+ guint16 dac_high,
+ guint16 dac_low,
+ guint16 sensor_subtype)
+{
+ GoodixMatchInfo *info = NULL;
+
+ (void) goodix_milan_match_extract_native_result (
+ image, preprocess_state, raw_frame, t_code, dac_high, dac_low,
+ sensor_subtype, &info);
+ return info;
+}
+
+GoodixMilanExtractionStatus
+goodix_milan_match_extract_native_result (
+ const guint8 *image,
+ GoodixMilanPreprocessState *preprocess_state,
+ const guint16 *raw_frame,
+ guint16 t_code,
+ guint16 dac_high,
+ guint16 dac_low,
+ guint16 sensor_subtype,
+ GoodixMatchInfo **info)
+{
+ if (info)
+ *info = NULL;
+ if (!image || !preprocess_state || !raw_frame ||
+ !preprocess_state->primary_contrast_valid || !info)
+ return GOODIX_MILAN_EXTRACTION_INVALID;
+
+ return goodix_milan_match_extract_planes (
+ image, preprocess_state->primary_contrast,
+ &preprocess_state->extraction_classification,
+ &preprocess_state->extraction_auxiliary,
+ preprocess_state->extraction_auxiliary_valid ?
+ preprocess_state->extraction_auxiliary_workspace : NULL,
+ preprocess_state->setup_map,
+ raw_frame, t_code, dac_high, dac_low, sensor_subtype,
+ preprocess_state->selected_refined, info, NULL);
+}
+
+#ifdef GOODIX53X5_DEBUG
+GoodixMilanExtractionStatus
+goodix_milan_match_extract_native_result_debug (
+ const guint8 *image,
+ GoodixMilanPreprocessState *preprocess_state,
+ const guint16 *raw_frame,
+ guint16 t_code,
+ guint16 dac_high,
+ guint16 dac_low,
+ guint16 sensor_subtype,
+ GoodixMatchInfo **info,
+ GoodixMilanExtractionDiagnostics *diagnostics)
+{
+ if (info)
+ *info = NULL;
+ if (diagnostics)
+ memset (diagnostics, 0, sizeof(*diagnostics));
+ if (!image || !preprocess_state || !raw_frame ||
+ !preprocess_state->primary_contrast_valid || !info)
+ return GOODIX_MILAN_EXTRACTION_INVALID;
+
+ return goodix_milan_match_extract_planes (
+ image, preprocess_state->primary_contrast,
+ &preprocess_state->extraction_classification,
+ &preprocess_state->extraction_auxiliary,
+ preprocess_state->extraction_auxiliary_valid ?
+ preprocess_state->extraction_auxiliary_workspace : NULL,
+ preprocess_state->setup_map,
+ raw_frame, t_code, dac_high, dac_low, sensor_subtype,
+ preprocess_state->selected_refined, info, diagnostics);
+}
+#endif
+
+static GoodixMilanExtractionStatus
+goodix_milan_match_extract_planes (const guint8 *image,
+ const guint8 *primary_contrast_plane,
+ GoodixMilanExtractionClassificationState *classification_state,
+ const GoodixMilanExtractionAuxiliaryState *auxiliary_state,
+ const guint8 *auxiliary_plane,
+ const guint16 *calibration,
+ const guint16 *raw_frame,
+ guint16 t_code,
+ guint16 dac_high,
+ guint16 dac_low,
+ guint16 sensor_subtype,
+ gint32 calibration_scalar,
+ GoodixMatchInfo **result,
+ GoodixMilanExtractionDiagnostics *diagnostics)
+{
+ GoodixMatchInfo *info = NULL;
+ guint8 *cropped = NULL;
+ guint8 *high = NULL;
+ guint8 *low = NULL;
+ guint8 *feature_mask = NULL;
+ guint8 *orientation = NULL;
+ guint8 *enhanced = NULL;
+ guint8 *enhanced_bitmap = NULL;
+ guint8 *inline_mask = NULL;
+ guint8 *validity_mask = NULL;
+ guint8 *broken_mask = NULL;
+ GoodixMilanAntifakeBlob *antifake = NULL;
+ GoodixMilanFeatureRecord *records = NULL;
+ guint8 *feature_element = NULL;
+ guint8 *milan_template = NULL;
+ guint8 tail_state[0x520] = { 0 };
+ GoodixMilanFeatureTemplateFields fields = { 0 };
+ size_t record_count = 0;
+ size_t zero_count = 0;
+ size_t record_limit;
+ size_t feature_element_size = 0;
+ size_t milan_template_size = 0;
+ guint8 enhanced_threshold;
+ guint8 published_class;
+ gint32 entry_low_class = 0;
+ gint32 entry_high_class = 0;
+ int quality;
+ int coverage;
+ GoodixMilanExtractionStatus status = GOODIX_MILAN_EXTRACTION_INVALID;
+
+ *result = NULL;
+ if (!image || !primary_contrast_plane || !classification_state ||
+ !auxiliary_state)
+ return status;
+ published_class = auxiliary_plane ? auxiliary_state->primary_histogram_state : 0;
+ info = g_new0 (GoodixMatchInfo, 1);
+ cropped = g_malloc (GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS);
+ high = g_malloc0 (286);
+ low = g_malloc0 (286);
+ feature_mask = g_malloc0 (52 * 44);
+ orientation = g_malloc (GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS);
+ enhanced = g_malloc (GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS);
+ enhanced_bitmap = g_malloc0 (286);
+ inline_mask = g_malloc0 (72);
+ validity_mask = g_malloc (GOODIX_MILAN_EXTRACTION_CLASSIFICATION_PIXELS);
+ antifake = g_malloc0 (sizeof(*antifake));
+ records = g_new0 (GoodixMilanFeatureRecord, 150);
+ feature_element = g_malloc (7945 + 150 * 32 + GOODIX_MILAN_OPTIONAL_C7_LEN);
+ milan_template = g_malloc (7945 + 150 * 32 + GOODIX_MILAN_OPTIONAL_C7_LEN +
+ 1433);
+ for (size_t row = 0;
+ row < GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS;
+ row++)
+ {
+ memcpy (cropped +
+ row * GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS,
+ image + row * GOODIX_MILAN_SENSOR_COLUMNS + 2,
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS);
+ }
+ if (sensor_subtype == GOODIX_MILAN_PRINT_SENSOR_TYPE)
+ goodix_milan_match_decode_entry_classes (
+ image, &fields.optional_c7, &entry_low_class, &entry_high_class,
+ &broken_mask);
+ if (goodix_milan_preprocess_quality (
+ image, GOODIX_MILAN_SENSOR_ROWS, GOODIX_MILAN_SENSOR_COLUMNS,
+ &quality, &coverage) != 0)
+ goto out;
+ record_limit = goodix_milan_match_record_limit (sensor_subtype, coverage, 150);
+ if (goodix_milan_feature_base_maps_with_validity (
+ image, GOODIX_MILAN_SENSOR_ROWS, GOODIX_MILAN_SENSOR_COLUMNS,
+ high, low, feature_mask, inline_mask, validity_mask) != 0 ||
+ goodix_milan_feature_enhance (
+ cropped, GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS,
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS, orientation,
+ enhanced) != 0 ||
+ goodix_milan_feature_enhanced_bitmap (
+ enhanced, feature_mask, GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS,
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS, enhanced_bitmap,
+ &enhanced_threshold) != 0)
+ goto out;
+ if (sensor_subtype == GOODIX_MILAN_PRINT_SENSOR_TYPE && auxiliary_plane)
+ {
+ /* Native commits history before record extraction, anti-fake, or packing
+ * failures. */
+ fields.optional_c7 = goodix_milan_match_update_extraction_classification (
+ classification_state, enhanced, validity_mask,
+ auxiliary_state->primary_histogram_state,
+ auxiliary_state->promoted_secondary_histogram_state, coverage,
+ entry_low_class, entry_high_class, &published_class, auxiliary_plane,
+ &info->classification);
+ if (!info->classification)
+ goto out;
+ }
+ if (goodix_milan_feature_extract_records_mode_masked (
+ image, GOODIX_MILAN_SENSOR_ROWS, GOODIX_MILAN_SENSOR_COLUMNS, records,
+ record_limit, &record_count, &zero_count, 1, broken_mask, validity_mask,
+ entry_high_class) != 0)
+ goto out;
+ if (broken_mask && entry_high_class >= 4)
+ /* The owned half-resolution mask was copied before filtering; only the
+ * later inline reduction observes the cleared dense validity mask. */
+ goodix_milan_feature_pack_inline_mask (
+ validity_mask, GOODIX_MILAN_EXTRACTION_CLASSIFICATION_ROWS,
+ GOODIX_MILAN_EXTRACTION_CLASSIFICATION_COLUMNS, inline_mask);
+ if (calibration && raw_frame &&
+ goodix_milan_antifake_build (
+ calibration, raw_frame, primary_contrast_plane, feature_mask,
+ 52 * 44,
+ GOODIX_MILAN_SENSOR_ROWS, GOODIX_MILAN_SENSOR_COLUMNS, t_code, dac_high,
+ dac_low,
+ sensor_subtype, calibration_scalar, antifake, sizeof(*antifake)) != 0)
+ goto out;
+ goodix_milan_debug_extraction_antifake (
+ diagnostics, calibration, raw_frame, primary_contrast_plane, feature_mask,
+ t_code, dac_high, dac_low, sensor_subtype, calibration_scalar);
+ goodix_milan_feature_mask_expand (inline_mask, feature_mask);
+ if (calibration && raw_frame &&
+ goodix_milan_template_initialize_tail (
+ image, GOODIX_MILAN_SENSOR_ROWS, GOODIX_MILAN_SENSOR_COLUMNS, tail_state,
+ sizeof(tail_state)) != 0)
+ goto out;
+ fields.tagged_values[2] = (int32_t) zero_count;
+ fields.tagged_values[3] = quality;
+ fields.tagged_values[4] = coverage;
+ if (goodix_milan_template_pack_feature_element (
+ high, enhanced_bitmap, inline_mask, low, records, record_count,
+ antifake, &fields, feature_element,
+ 7945 + 150 * 32 + GOODIX_MILAN_OPTIONAL_C7_LEN,
+ &feature_element_size) != 0 ||
+ goodix_milan_template_pack_one_feature (
+ feature_element, feature_element_size, tail_state, sizeof(tail_state),
+ milan_template,
+ 7945 + 150 * 32 + GOODIX_MILAN_OPTIONAL_C7_LEN + 1433,
+ &milan_template_size) != 0)
+ goto out;
+ info->template = g_bytes_new_take (milan_template, milan_template_size);
+ milan_template = NULL;
+ info->record_count = (int) record_count;
+ info->partition_count = (int) zero_count;
+ memcpy (info->feature_bitmaps.high_bitmap, high,
+ sizeof(info->feature_bitmaps.high_bitmap));
+ memcpy (info->feature_bitmaps.enhanced_bitmap, enhanced_bitmap,
+ sizeof(info->feature_bitmaps.enhanced_bitmap));
+ memcpy (info->feature_bitmaps.low_bitmap, low,
+ sizeof(info->feature_bitmaps.low_bitmap));
+ memcpy (info->inline_mask, inline_mask, sizeof(info->inline_mask));
+ goodix_milan_match_pack_rescue_mask (feature_mask, info->rescue_mask);
+ memcpy (&info->antifake, antifake, sizeof(info->antifake));
+ info->records = records;
+ info->extraction_metadata.quality = quality;
+ info->extraction_metadata.coverage = coverage;
+ info->extraction_metadata.optional_c7 = fields.optional_c7;
+ if (auxiliary_plane)
+ info->extraction_metadata.auxiliary = *auxiliary_state;
+ /* Live classification publishes the history-promoted mode, independently of
+ * the preprocessing seed and the packed c7 high class. */
+ info->extraction_metadata.auxiliary.primary_histogram_state = published_class;
+ records = NULL;
+ status = GOODIX_MILAN_EXTRACTION_OK;
+
+out:
+ g_free (milan_template);
+ g_free (feature_element);
+ g_free (records);
+ g_free (antifake);
+ g_free (broken_mask);
+ g_free (validity_mask);
+ g_free (inline_mask);
+ g_free (enhanced_bitmap);
+ g_free (enhanced);
+ g_free (orientation);
+ g_free (feature_mask);
+ g_free (low);
+ g_free (high);
+ g_free (cropped);
+ if (!info->template)
+ g_clear_pointer (&info, goodix_milan_match_free_info);
+ *result = info;
+ return status;
+}
+
+int
+goodix_milan_match_keypoints_count (GoodixMatchInfo *info)
+{
+ return info ? info->record_count : 0;
+}
+
+GoodixMatchInfo *
+goodix_milan_match_info_new_empty (void)
+{
+ return g_new0 (GoodixMatchInfo, 1);
+}
+
+void
+goodix_milan_match_info_clear (GoodixMatchInfo *info)
+{
+ if (!info)
+ return;
+ g_clear_pointer (&info->template, g_bytes_unref);
+ g_clear_pointer (&info->records, g_free);
+ g_clear_pointer (&info->classification, g_bytes_unref);
+ memset (info, 0, sizeof(*info));
+}
+
+gboolean
+goodix_milan_match_info_is_complete (const GoodixMatchInfo *info)
+{
+ return info && info->template && info->records && info->record_count > 0 &&
+ info->record_count <= 150 && info->partition_count >= 0 &&
+ info->partition_count <= info->record_count;
+}
+
+gboolean
+goodix_milan_match_info_copy (GoodixMatchInfo *destination,
+ const GoodixMatchInfo *source)
+{
+ GoodixMatchInfo copy = { 0 };
+ const guint8 *template_data;
+ gsize template_size;
+
+ if (!destination || !goodix_milan_match_info_is_complete (source))
+ return FALSE;
+ template_data = g_bytes_get_data (source->template, &template_size);
+ copy.template = g_bytes_new (template_data, template_size);
+ copy.records = g_memdup2 (
+ source->records,
+ (gsize) source->record_count * sizeof(*source->records));
+ for (int i = 0; i < source->record_count; i++)
+ {
+ memset (copy.records[i].payload + 24, 0, 4);
+ memset (copy.records[i].payload + 36, 0, 8);
+ }
+ copy.record_count = source->record_count;
+ copy.partition_count = source->partition_count;
+ memcpy (copy.feature_bitmaps.high_bitmap,
+ source->feature_bitmaps.high_bitmap,
+ sizeof(copy.feature_bitmaps.high_bitmap));
+ memcpy (copy.feature_bitmaps.enhanced_bitmap,
+ source->feature_bitmaps.enhanced_bitmap,
+ sizeof(copy.feature_bitmaps.enhanced_bitmap));
+ memcpy (copy.feature_bitmaps.low_bitmap,
+ source->feature_bitmaps.low_bitmap,
+ sizeof(copy.feature_bitmaps.low_bitmap));
+ memcpy (copy.inline_mask, source->inline_mask, sizeof(copy.inline_mask));
+ memcpy (copy.rescue_mask, source->rescue_mask, sizeof(copy.rescue_mask));
+ memcpy (©.antifake, &source->antifake, sizeof(copy.antifake));
+ copy.extraction_metadata = source->extraction_metadata;
+ /* FUN_180045a50 does not transfer the live histogram/plane owner. Both
+ * callers create queue or gallery owners, which have no live summary. */
+ memset (©.extraction_metadata.auxiliary, 0,
+ sizeof(copy.extraction_metadata.auxiliary));
+
+ goodix_milan_match_info_clear (destination);
+ *destination = copy;
+ return TRUE;
+}
+
+void
+goodix_milan_match_free_info (GoodixMatchInfo *info)
+{
+ if (!info)
+ return;
+ goodix_milan_match_info_clear (info);
+ g_free (info);
+}
diff --git a/libfprint/drivers/goodix53x5/milan/match/lifecycle-private.h b/libfprint/drivers/goodix53x5/milan/match/lifecycle-private.h
new file mode 100644
index 0000000..af2fcda
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/lifecycle-private.h
@@ -0,0 +1,32 @@
+/*
+ * Goodix 53x5 driver for libfprint - Milan serialized match lifecycle internals
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ */
+
+#pragma once
+
+#include "milan/match/match.h"
+#include "milan/study/queue.h"
+
+gboolean goodix_milan_match_queue_matches_template (const GoodixStudyQueue *queue,
+ const guint8 *feature,
+ gsize feature_len);
+
+GoodixSigfmTemplateStatus goodix_milan_match_serialized_feature_result_internal (GoodixMatchInfo *probe_info,
+ const guint8 *feature,
+ gsize feature_len,
+ GoodixMilanMatchResult *match_result,
+ GBytes **updated_feature,
+#ifdef GOODIX53X5_DEBUG
+ GoodixMilanMatchDiagnostics *diagnostics,
+#endif
+ GoodixStudyQueue *queue,
+ gboolean normalize,
+ GoodixStudyQueueEnqueueResult (*enqueue_candidate) (
+ GoodixStudyQueue *queue,
+ const GoodixMatchInfo *probe_info));
diff --git a/libfprint/drivers/goodix53x5/milan/match/lifecycle.c b/libfprint/drivers/goodix53x5/milan/match/lifecycle.c
new file mode 100644
index 0000000..dc0baaf
--- /dev/null
+++ b/libfprint/drivers/goodix53x5/milan/match/lifecycle.c
@@ -0,0 +1,372 @@
+/*
+ * Goodix 53x5 driver for libfprint - native Milan serialized match lifecycle
+ * Copyright (C) 2026 goodix-fp-linux-dev contributors
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#define FP_COMPONENT "goodix53x5"
+
+#include "drivers_api.h"
+#include "milan/match/match.h"
+#include "milan/match/info-private.h"
+#include "milan/match/lifecycle-private.h"
+#include "milan/milan.h"
+#include "milan/private.h"
+#include "milan/print.h"
+#include "milan/study/queue.h"
+
+#include <string.h>
+
+static int
+milan_match_decode_imported_angles (
+ const guint8 *source,
+ gsize source_size,
+ GoodixMilanUnpackedTemplate *unpacked,
+ GoodixMatchInfo *decoded[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY])
+{
+ g_autoptr(GBytes) identity = NULL;
+ int changed = 0;
+
+ for (size_t i = 0; i < unpacked->feature_count; i++)
+ {
+ GoodixMilanFeatureView view;
+ gboolean has_negative = FALSE;
+
+ if (goodix_milan_template_parse_feature_element (
+ unpacked->feature_elements[i], unpacked->feature_element_sizes[i],
+ &view) != 0 || view.record_count == 0 || view.record_count > 150 ||
+ view.fields.tagged_values[2] < 0 ||
+ (size_t) view.fields.tagged_values[2] > view.record_count)
+ continue;
+ /* The sign-magnitude byte 0x80 decodes to zero, not a negative word. */
+ for (size_t j = 0; j < view.record_count; j++)
+ has_negative |= view.packed_records[j * 32] > 0x80;
+ if (!has_negative)
+ continue;
+
+ if (!identity)
+ identity = g_bytes_new (source, source_size);
+ decoded[i] = goodix_milan_match_info_new_empty ();
+ /* Keep an immutable identity; gallery overrides consume only records/counts. */
+ decoded[i]->template = g_bytes_ref (identity);
+ decoded[i]->record_count = (int) view.record_count;
+ decoded[i]->partition_count = view.fields.tagged_values[2];
+ decoded[i]->records = g_new (GoodixMilanFeatureRecord, view.record_count);
+ if (goodix_milan_feature_unpack_template_records (
+ view.packed_records, view.record_count,
+ (size_t) view.fields.tagged_values[2], decoded[i]->records,
+ view.record_count) != 0)
+ return -1;
+ for (size_t j = 0; j < view.record_count; j++)
+ if (decoded[i]->records[j].orientation < 0)
+ decoded[i]->records[j].orientation =
+ (int16_t) (decoded[i]->records[j].orientation + 0x3244);
+ /* Native pack quantizes the adjusted angle; retained matching must still
+ * use the exact live word rather than decode that lossy projection. */
+ if (goodix_milan_feature_pack_template_records (
+ decoded[i]->records, view.record_count,
+ (guint8 *) view.packed_records, view.record_count * 32) != 0)
+ return -1;
+ changed++;
+ }
+ return changed;
+}
+
+gboolean
+goodix_milan_match_queue_matches_template (const GoodixStudyQueue *queue,
+ const guint8 *feature,
+ gsize feature_len)
+{
+ GoodixMilanUnpackedTemplate *unpacked;
+ gboolean matches = FALSE;
+
+ if (!queue || !goodix_milan_study_queue_validate (queue))
+ return FALSE;
+ if (!feature || feature_len > GOODIX_MILAN_TEMPLATE_MAX_SIZE)
+ return FALSE;
+ unpacked = g_malloc (sizeof(*unpacked));
+ if (goodix_milan_template_unpack (feature, feature_len, unpacked) == 0)
+ matches = queue->enabled_state == unpacked->metadata.queue_state &&
+ queue->transaction_counter ==
+ unpacked->metadata.queue_transaction_counter;
+ g_free (unpacked);
+ return matches;
+}
+
+GoodixSigfmTemplateStatus
+goodix_milan_match_serialized_feature_result_internal (
+ GoodixMatchInfo *probe_info,
+ const guint8 *feature,
+ gsize feature_len,
+ GoodixMilanMatchResult *match_result,
+ GBytes **updated_feature,
+#ifdef GOODIX53X5_DEBUG
+ GoodixMilanMatchDiagnostics *diagnostics,
+#endif
+ GoodixStudyQueue *queue,
+ gboolean normalize,
+ GoodixStudyQueueEnqueueResult (*enqueue_candidate) (
+ GoodixStudyQueue *queue,
+ const GoodixMatchInfo *probe_info))
+{
+ guint8 *updated_milan = NULL;
+ guint8 *normalized_milan = NULL;
+ const guint8 *matched_milan;
+ size_t normalized_milan_len = 0;
+ size_t updated_milan_len = 0;
+ GoodixMilanUnpackedTemplate *unpacked;
+ gboolean retained_gallery;
+ const GoodixMilanFeatureRecord *live_records[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+ size_t live_record_counts[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+ size_t live_partition_counts[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+ GoodixMatchInfo *decoded_features[GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY] = { 0 };
+ GBytes *private_update = NULL;
+ GBytes *input_identity = NULL;
+ const guint8 *requested_feature = feature;
+ gsize requested_size = feature_len;
+ gboolean publish_result = updated_feature != NULL;
+
+ if (queue && !updated_feature)
+ updated_feature = &private_update;
+ if (updated_feature)
+ *updated_feature = NULL;
+
+ if (!probe_info || !probe_info->template || !feature || !match_result)
+ goto invalid;
+ if (queue && !goodix_milan_study_queue_validate (queue))
+ goto invalid;
+ retained_gallery = goodix_milan_study_queue_resolve_gallery (
+ queue, &feature, &feature_len);
+ gsize enrolled_milan_len = feature_len;
+ const guint8 *enrolled_milan = feature;
+
+ if (feature_len > GOODIX_MILAN_TEMPLATE_MAX_SIZE)
+ goto invalid;
+ if (queue && !goodix_milan_match_queue_matches_template (
+ queue, feature, feature_len))
+ goto invalid;
+ if (queue && !publish_result)
+ input_identity = g_bytes_new (requested_feature, requested_size);
+ if (retained_gallery)
+ {
+ normalize = FALSE;
+ for (size_t i = 0; i < GOODIX_MILAN_TEMPLATE_FEATURE_CAPACITY; i++)
+ if (queue->live_features[i])
+ {
+ live_records[i] = queue->live_features[i]->records;
+ live_record_counts[i] = queue->live_features[i]->record_count;
+ live_partition_counts[i] = queue->live_features[i]->partition_count;
+ }
+ }
+ normalized_milan = g_malloc (enrolled_milan_len);
+ if (normalize)
+ {
+ if (goodix_milan_template_normalize (
+ enrolled_milan, enrolled_milan_len, normalized_milan,
+ enrolled_milan_len, &normalized_milan_len) != 0)
+ {
+ g_free (normalized_milan);
+ goto invalid;
+ }
+ }
+ else
+ {
+ memcpy (normalized_milan, enrolled_milan, enrolled_milan_len);
+ normalized_milan_len = enrolled_milan_len;
+ }
+ if (normalized_milan_len != enrolled_milan_len)
+ {
+ g_free (normalized_milan);
+ goto invalid;
+ }
+ unpacked = g_malloc (sizeof (*unpacked));
+ if (goodix_milan_template_unpack (
+ normalized_milan, normalized_milan_len, unpacked) == 0 &&
+ unpacked->metadata.sensor_type == GOODIX_MILAN_PRINT_SENSOR_TYPE)
+ {
+ for (size_t i = 0; i < unpacked->feature_count; i++)
+ {
+ GoodixMilanFeatureView view;
+
+ if (goodix_milan_template_parse_feature_element (
+ unpacked->feature_elements[i], unpacked->feature_element_sizes[i],
+ &view) != 0)
+ continue;
+ /* Ordinary native dispatch resets every gallery owner before traversal,
+ * including retained galleries and rows that matching later skips. */
+ if (view.fields.tagged_values[5] == 5)
+ {
+ if (goodix_milan_template_patch_feature_scalar (
+ (guint8 *) unpacked->feature_elements[i],
+ unpacked->feature_element_sizes[i], 0xba, 0) != 0)
+ {
+ g_free (unpacked);
+ g_free (updated_milan);
+ g_free (normalized_milan);
+ goto invalid;
+ }
+ if (!updated_milan)
+ updated_milan = g_malloc (normalized_milan_len);
+ }
+ if (!retained_gallery && view.record_count > 0 &&
+ view.record_count <= 150 &&
+ view.fields.tagged_values[2] == (int32_t) view.record_count)
+ {
+ /* Unpack borrows our writable gallery copy, never the probe. */
+ if (goodix_milan_template_patch_feature_scalar (
+ (guint8 *) unpacked->feature_elements[i],
+ unpacked->feature_element_sizes[i], 0xb7,
+ (int32_t) view.record_count - 1) != 0)
+ {
+ g_free (unpacked);
+ g_free (updated_milan);
+ g_free (normalized_milan);
+ goto invalid;
+ }
+ if (!updated_milan)
+ updated_milan = g_malloc (normalized_milan_len);
+ }
+ }
+ if (!retained_gallery)
+ {
+ int changed = milan_match_decode_imported_angles (
+ enrolled_milan, enrolled_milan_len, unpacked, decoded_features);
+
+ if (changed < 0)
+ {
+ g_free (unpacked);
+ g_free (updated_milan);
+ g_free (normalized_milan);
+ goto invalid;
+ }
+ if (changed && !updated_milan)
+ updated_milan = g_malloc (normalized_milan_len);
+ for (size_t i = 0; i < unpacked->feature_count; i++)
+ if (decoded_features[i])
+ {
+ live_records[i] = decoded_features[i]->records;
+ live_record_counts[i] = decoded_features[i]->record_count;
+ live_partition_counts[i] = decoded_features[i]->partition_count;
+ }
+ }
+ }
+ if (updated_milan)
+ {
+ if (goodix_milan_template_pack (
+ unpacked->feature_elements, unpacked->feature_element_sizes,
+ unpacked->feature_count, unpacked->relations, unpacked->relation_count,
+ &unpacked->metadata, unpacked->tail_state, sizeof (unpacked->tail_state),
+ updated_milan, normalized_milan_len, &updated_milan_len) != 0 ||
+ updated_milan_len != normalized_milan_len)
+ {
+ g_free (unpacked);
+ g_free (updated_milan);
+ g_free (normalized_milan);
+ goto invalid;
+ }
+ g_free (normalized_milan);
+ normalized_milan = g_steal_pointer (&updated_milan);
+ }
+ g_free (unpacked);
+ matched_milan = normalized_milan;
+
+ if (goodix_milan_match_info_result (
+ probe_info, matched_milan, normalized_milan_len,
+ live_records, live_record_counts, live_partition_counts,
+ SIZE_MAX, match_result
+#ifdef GOODIX53X5_DEBUG
+ , diagnostics
+#endif
+ ) != 0)
+ {
+ g_free (normalized_milan);
+ goto invalid;
+ }
+
+ if (updated_feature)
+ {
+ if (match_resuFile truncated at 1 MB.