950 lines
50 KiB
Java
950 lines
50 KiB
Java
package com.it_screen.edgevision;
|
||
|
||
import android.Manifest;
|
||
import android.app.Activity;
|
||
import android.content.Intent;
|
||
import android.content.SharedPreferences;
|
||
import android.content.pm.PackageManager;
|
||
import android.graphics.*;
|
||
import android.hardware.camera2.CameraManager;
|
||
import android.os.*;
|
||
import android.view.*;
|
||
import android.widget.*;
|
||
import java.util.*;
|
||
import java.util.concurrent.ExecutorService;
|
||
import java.util.concurrent.Executors;
|
||
import java.util.concurrent.atomic.AtomicBoolean;
|
||
import java.util.concurrent.atomic.AtomicLong;
|
||
import org.json.JSONObject;
|
||
|
||
public final class MainActivity extends Activity {
|
||
private final ExecutorService inference = Executors.newSingleThreadExecutor();
|
||
private final AtomicBoolean busy = new AtomicBoolean();
|
||
private final AtomicBoolean previewQueued = new AtomicBoolean();
|
||
private final AtomicLong skipped = new AtomicLong();
|
||
private final PersonTracker tracker = new PersonTracker();
|
||
private static final int DEFAULT_REID_THRESHOLD = 55;
|
||
private final ReIdProvider<float[]> reId = FaceReId.create();
|
||
private final VisitorSessions<float[]> visitorSessions = new VisitorSessions<>(reId);
|
||
private final ArrayDeque<String> visitEvents = new ArrayDeque<>();
|
||
private final AudienceAggregator totals = new AudienceAggregator();
|
||
private final Benchmark benchmark = new Benchmark();
|
||
private final Handler ui = new Handler(Looper.getMainLooper());
|
||
private final long startedAt = SystemClock.elapsedRealtime();
|
||
private volatile long generation, nextFrame;
|
||
private volatile Bitmap previewFrame;
|
||
private VideoSource source;
|
||
private InferenceEngine engine;
|
||
private ModelRegistry registry;
|
||
private Settings loaded;
|
||
private YuNet detector;
|
||
private CydralDemographics demographics;
|
||
private NanoDetPerson personDetector;
|
||
private long nextFaceFrame;
|
||
private SharedPreferences preferences;
|
||
private List<ModelRegistry.Entry> faceModels, demographicModels;
|
||
private List<String> providers;
|
||
private long metricsEpoch, frameCount, lastCpu, lastCpuAt, errors;
|
||
private double aiFps;
|
||
private double loadMs;
|
||
private final Runnable expirePocSessions = this::expirePocSessions;
|
||
private TextView status, currentVisitorValue, trackingLog, uniqueValue, repeatedValue, sessionValue;
|
||
private DiagnosticsPanel diagnostics;
|
||
private ResourcePanel resources;
|
||
private TextView cameraStatus;
|
||
private final java.text.SimpleDateFormat eventClock = new java.text.SimpleDateFormat("HH:mm:ss", Locale.ROOT);
|
||
private Preview preview;
|
||
private Button start, stop, test;
|
||
private Spinner resolution, interval, detection, classification, provider, threadCount, faceModel, ageModel;
|
||
private boolean running;
|
||
|
||
@Override public void onCreate(Bundle state) {
|
||
super.onCreate(state);
|
||
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
|
||
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
|
||
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
|
||
if (FaceReId.CONTROLLED_POC) getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
|
||
preferences = getSharedPreferences("aggregates", MODE_PRIVATE);
|
||
totals.visits = preferences.getInt("total", 0);
|
||
readCounts("age", totals.ages);
|
||
readCounts("gender", totals.genders);
|
||
createDashboard();
|
||
updateStats(0, totals.visits, totals.genders.clone(), totals.ages.clone());
|
||
try {
|
||
registry = new ModelRegistry(getAssets());
|
||
engine = new OrtEngine(registry, getCacheDir());
|
||
providers = new ArrayList<>(engine.providers());
|
||
providers.retainAll(List.of("CPU", "XNNPACK", "NNAPI"));
|
||
providers.sort(Comparator.comparingInt(List.of("CPU", "XNNPACK", "NNAPI")::indexOf));
|
||
faceModels = registry.list("face");
|
||
demographicModels = registry.list("age");
|
||
choices(provider, providers);
|
||
if (providers.contains("XNNPACK")) provider.setSelection(providers.indexOf("XNNPACK"));
|
||
choices(faceModel, faceModels);
|
||
for (int i = 0; i < faceModels.size(); i++) {
|
||
if (faceModels.get(i).json.optString("version").equals("2026may-fixed320")) faceModel.setSelection(i);
|
||
}
|
||
choices(ageModel, demographicModels);
|
||
configureSizes();
|
||
setStatus("Ready · adult volunteers only");
|
||
setRunning(false);
|
||
} catch (Exception | LinkageError error) {
|
||
setStatus("Initialization error: " + error);
|
||
start.setEnabled(false);
|
||
test.setEnabled(false);
|
||
}
|
||
}
|
||
|
||
private void readCounts(String prefix, int[] counts) {
|
||
for (int i = 0; i < counts.length; i++) counts[i] = preferences.getInt(prefix + i, 0);
|
||
}
|
||
|
||
private void persist() {
|
||
SharedPreferences.Editor write = preferences.edit().putInt("total", totals.visits);
|
||
for (int i = 0; i < totals.ages.length; i++) write.putInt("age" + i, totals.ages[i]);
|
||
for (int i = 0; i < totals.genders.length; i++) write.putInt("gender" + i, totals.genders[i]);
|
||
write.apply();
|
||
}
|
||
|
||
private void configureSizes() {
|
||
try {
|
||
SizeList list = new SizeList(InternalCamera.sizes((CameraManager) getSystemService(CAMERA_SERVICE)));
|
||
choices(resolution, list.values);
|
||
if (list.values.contains("640×480")) resolution.setSelection(list.values.indexOf("640×480"));
|
||
} catch (Exception error) {
|
||
android.util.Log.w("EdgeVision", "Camera sizes unavailable before permission", error);
|
||
}
|
||
}
|
||
|
||
private static final class SizeList {
|
||
final List<String> values = new ArrayList<>();
|
||
SizeList(android.util.Size[] input) {
|
||
Arrays.sort(input, Comparator.comparingLong(s -> (long) s.getWidth() * s.getHeight()));
|
||
for (android.util.Size size : input) values.add(size.getWidth() + "×" + size.getHeight());
|
||
}
|
||
}
|
||
|
||
private void createDashboard() {
|
||
LinearLayout root = new LinearLayout(this);
|
||
root.setOrientation(LinearLayout.HORIZONTAL);
|
||
root.setBackgroundColor(0xff101821);
|
||
LinearLayout left = column();
|
||
left.setPadding(16, 10, 12, 10);
|
||
root.addView(left, new LinearLayout.LayoutParams(0, -1, 2));
|
||
String appName = getApplicationInfo().loadLabel(getPackageManager()).toString();
|
||
TextView title = text(appName + " v" + appVersion(), 22);
|
||
title.setSingleLine(true);
|
||
title.setEllipsize(android.text.TextUtils.TruncateAt.END);
|
||
left.addView(title);
|
||
status = text("Initializing…", 14);
|
||
left.addView(status);
|
||
preview = new Preview();
|
||
left.addView(preview, new LinearLayout.LayoutParams(-1, 0, 1));
|
||
LinearLayout cameraRow = new LinearLayout(this);
|
||
cameraRow.setGravity(Gravity.CENTER_VERTICAL);
|
||
cameraStatus = text("Камера · остановлена", 14);
|
||
cameraRow.addView(cameraStatus, new LinearLayout.LayoutParams(0, -2, 2));
|
||
resolution = setting(cameraRow, "Разрешение до запуска", "640×480", "1280×720");
|
||
left.addView(cameraRow);
|
||
resources = new ResourcePanel(this);
|
||
left.addView(resources);
|
||
LinearLayout actions = new LinearLayout(this);
|
||
left.addView(actions);
|
||
start = button(actions, "Start", () -> {
|
||
if (FaceReId.CONTROLLED_POC) {
|
||
new android.app.AlertDialog.Builder(this)
|
||
.setTitle("Face Re-ID · согласие на тест")
|
||
.setMessage("Проводите тест только со взрослыми, которые согласились на локальное сопоставление лиц. " +
|
||
"Шаблоны хранятся в памяти до таймаута или остановки камеры. Убедитесь, что посторонних нет в кадре.")
|
||
.setNegativeButton("Отмена", null)
|
||
.setPositiveButton("Согласие получено", (dialog, which) -> requestCamera())
|
||
.show();
|
||
} else requestCamera();
|
||
});
|
||
stop = button(actions, "Stop", () -> halt("Camera stopped"));
|
||
button(actions, "Reset Statistics", this::reset);
|
||
button(actions, "Export Benchmark", () -> inference.execute(() -> {
|
||
try {
|
||
java.io.File file = benchmark.save(getExternalFilesDir("benchmark"));
|
||
ui.post(() -> Toast.makeText(this, "Saved " + file.getName() + " JSON / CSV", Toast.LENGTH_LONG).show());
|
||
} catch (Exception error) { ui.post(() -> setStatus(error.toString())); }
|
||
}));
|
||
test = button(actions, "Test Image", () -> {
|
||
Intent picker = new Intent(Intent.ACTION_OPEN_DOCUMENT).setType("image/*").addCategory(Intent.CATEGORY_OPENABLE);
|
||
startActivityForResult(picker, 2);
|
||
});
|
||
button(actions, "Tracking settings", this::editTrackingSettings);
|
||
LinearLayout row1 = new LinearLayout(this), row2 = new LinearLayout(this);
|
||
left.addView(row1);
|
||
left.addView(row2);
|
||
interval = setting(row1, "Face interval ms", "100", "200", "500", "1000");
|
||
interval.setSelection(2);
|
||
detection = setting(row1, "Detection threshold", "0.5", "0.6", "0.7", "0.8", "0.9");
|
||
detection.setSelection(1);
|
||
classification = setting(row1, "Class. threshold", "0.6", "0.7", "0.8", "0.9", "0.95");
|
||
classification.setSelection(2);
|
||
provider = setting(row2, "Execution provider", "CPU");
|
||
threadCount = setting(row2, "Threads", "1", "2", "3", "4");
|
||
threadCount.setSelection(1);
|
||
faceModel = setting(row2, "Detector", "Loading");
|
||
ageModel = setting(row2, "Age / gender", "Loading");
|
||
LinearLayout right = column();
|
||
right.setBackgroundColor(0xff1a2833);
|
||
right.setPadding(14, 10, 12, 10);
|
||
root.addView(right, new LinearLayout.LayoutParams(0, -1, 1));
|
||
diagnostics = new DiagnosticsPanel(this);
|
||
LinearLayout currentVisitorRow = new LinearLayout(this);
|
||
currentVisitorRow.setGravity(Gravity.CENTER_VERTICAL);
|
||
TextView currentVisitorLabel = text("Current visitors", 16);
|
||
currentVisitorLabel.setTypeface(Typeface.DEFAULT_BOLD);
|
||
currentVisitorRow.addView(currentVisitorLabel, new LinearLayout.LayoutParams(0, -2, 1));
|
||
currentVisitorValue = text("0", 32);
|
||
currentVisitorValue.setTextColor(0xff9ce8c2);
|
||
currentVisitorValue.setTypeface(Typeface.DEFAULT_BOLD);
|
||
currentVisitorRow.addView(currentVisitorValue);
|
||
right.addView(currentVisitorRow);
|
||
TextView currentVisitorNote = text("Оценка числа людей, которых камера сейчас видит.", 13);
|
||
currentVisitorNote.setTextColor(0xffaebfd1);
|
||
currentVisitorNote.setPadding(0, 4, 0, 6);
|
||
right.addView(currentVisitorNote);
|
||
if (FaceReId.CONTROLLED_POC) {
|
||
uniqueValue = counter(right, "Unique Visitors · оценка PoC");
|
||
repeatedValue = counter(right, "Повторные обнаружения");
|
||
sessionValue = counter(right, "Активные Visitor Sessions");
|
||
TextView note = text("За текущий запуск камеры. Пока лицо не сопоставлено, неопределённый трек в оценку не входит.", 13);
|
||
note.setTextColor(0xffaebfd1);
|
||
right.addView(note);
|
||
} else right.addView(text("Уникальные посетители — пока не считаются", 14));
|
||
|
||
TextView journalTitle = text("Журнал трекинга", 16);
|
||
journalTitle.setPadding(0, 16, 0, 6);
|
||
right.addView(journalTitle);
|
||
ScrollView terminal = new ScrollView(this);
|
||
terminal.setFillViewport(true);
|
||
android.graphics.drawable.GradientDrawable frame = new android.graphics.drawable.GradientDrawable();
|
||
frame.setColor(0xff101821);
|
||
frame.setStroke(1, 0xff587181);
|
||
frame.setCornerRadius(6);
|
||
terminal.setBackground(frame);
|
||
right.addView(terminal, new LinearLayout.LayoutParams(-1, 0, 1));
|
||
trackingLog = text("Ожидание посетителей", 13);
|
||
trackingLog.setTypeface(Typeface.MONOSPACE);
|
||
trackingLog.setTextColor(0xff9ce8c2);
|
||
trackingLog.setPadding(10, 9, 10, 9);
|
||
trackingLog.setLineSpacing(3, 1);
|
||
terminal.addView(trackingLog);
|
||
LinearLayout diagnosticsActions = new LinearLayout(this);
|
||
diagnosticsActions.setGravity(Gravity.END);
|
||
button(diagnosticsActions, "More", diagnostics::show);
|
||
right.addView(diagnosticsActions);
|
||
setContentView(root);
|
||
start.setEnabled(false);
|
||
test.setEnabled(false);
|
||
}
|
||
|
||
private TextView counter(LinearLayout parent, String name) {
|
||
LinearLayout row = new LinearLayout(this);
|
||
TextView label = text(name, 15);
|
||
label.setTypeface(Typeface.DEFAULT_BOLD);
|
||
row.addView(label, new LinearLayout.LayoutParams(0, -2, 1));
|
||
TextView value = text("0", 18);
|
||
value.setTextColor(0xff9ce8c2);
|
||
row.addView(value);
|
||
parent.addView(row);
|
||
return value;
|
||
}
|
||
|
||
private void updatePocStats(long unique, long repeats, int sessions) {
|
||
if (!FaceReId.CONTROLLED_POC) return;
|
||
updateCounter(uniqueValue, unique);
|
||
updateCounter(repeatedValue, repeats);
|
||
updateCounter(sessionValue, sessions);
|
||
}
|
||
|
||
private void updateCounter(TextView view, long count) {
|
||
String value = Long.toString(count);
|
||
if (!value.contentEquals(view.getText())) view.setText(value);
|
||
}
|
||
|
||
private void editTrackingSettings() {
|
||
LinearLayout form = column();
|
||
form.setPadding(24, 10, 24, 10);
|
||
form.setFocusableInTouchMode(true);
|
||
EditText confirmation = trackingField(form, "Confirmation Time (ms)", "tracking_confirm_ms", 1000,
|
||
"Сколько времени человек должен наблюдаться, чтобы трек подтвердился и учитывался в Current visitors. 1000 мс = 1 с.");
|
||
EditText lost = trackingField(form, "Lost Track Timeout (ms)", "tracking_lost_ms", 10000,
|
||
"Сколько времени хранится ID трека после последнего обнаружения. Если трек восстановится в это время, ID сохранится. 10 000 мс = 10 с.");
|
||
TextView fpsLabel = trackingSettingLabel(form, "Target Tracking FPS");
|
||
Spinner fps = new Spinner(this);
|
||
fps.setId(View.generateViewId());
|
||
fpsLabel.setLabelFor(fps.getId());
|
||
fps.setContentDescription("Target Tracking FPS");
|
||
List<Integer> fpsOptions = new ArrayList<>();
|
||
for (int rate = 1; rate <= 15; rate++) fpsOptions.add(rate);
|
||
choices(fps, fpsOptions);
|
||
fps.setSelection(Math.max(1, Math.min(15, preferences.getInt("tracking_fps", 5))) - 1);
|
||
form.addView(fps);
|
||
trackingSettingNote(form, "Сколько кадров в секунду трекер старается обработать. Большее значение помогает при быстром движении и повышает нагрузку. Фактическая частота видна в More.");
|
||
EditText visitorTimeout = trackingField(form, "Visitor Session Timeout (minutes)",
|
||
"visitor_session_timeout_minutes", VisitorSessions.DEFAULT_TIMEOUT_MINUTES,
|
||
"Сколько минут с последнего обнаружения открыта сессия посетителя, даже если трек закрылся. Таймаут сам по себе не связывает разные треки.");
|
||
trackingSettingLabel(form, "Count Once Per Track: true");
|
||
trackingSettingNote(form, "Фиксированный режим. Каждый подтверждённый трек учитывается один раз в Confirmed Tracks. Восстановление того же ID не добавляет трек в счётчик.");
|
||
EditText similarity = FaceReId.CONTROLLED_POC ? trackingField(form, "Re-ID Similarity Threshold (%)",
|
||
"reid_similarity_percent", DEFAULT_REID_THRESHOLD,
|
||
"Минимальное косинусное сходство. Чем выше порог, тем сложнее связать разные треки. Это не вероятность. При близких кандидатах совпадение отмечается как неопределённое.") : null;
|
||
trackingSettingLabel(form, FaceReId.CONTROLLED_POC ? "Biometric Matching · SFace PoC" : "Biometric Matching: false");
|
||
trackingSettingNote(form, FaceReId.CONTROLLED_POC ?
|
||
"Сопоставление выполняется локально. При Stop и истечении таймаута шаблоны удаляются из памяти." :
|
||
"Сопоставление людей между разными треками отключено.");
|
||
trackingSettingNote(form, "Таймаут сессии и порог Re-ID применяются сразу. Настройки трекинга вступают в силу при следующем Start.");
|
||
ScrollView fields = new ScrollView(this);
|
||
fields.addView(form);
|
||
android.app.AlertDialog dialog = new android.app.AlertDialog.Builder(this)
|
||
.setTitle("Tracking settings").setView(fields)
|
||
.setNegativeButton("Cancel", null).setPositiveButton("Save", null).create();
|
||
dialog.setOnShowListener(ignored -> dialog.getButton(android.app.AlertDialog.BUTTON_POSITIVE)
|
||
.setOnClickListener(button -> {
|
||
try {
|
||
int confirmationMs = Integer.parseInt(confirmation.getText().toString());
|
||
int lostMs = Integer.parseInt(lost.getText().toString());
|
||
int trackingFps = (Integer) fps.getSelectedItem();
|
||
int visitorTimeoutMinutes = Integer.parseInt(visitorTimeout.getText().toString());
|
||
int threshold = similarity == null ? DEFAULT_REID_THRESHOLD :
|
||
Integer.parseInt(similarity.getText().toString());
|
||
if (threshold < 1 || threshold > 100 || confirmationMs < 0 || confirmationMs > 10000 || lostMs < 1000 ||
|
||
lostMs > 120000 || trackingFps < 1 || trackingFps > 15 ||
|
||
visitorTimeoutMinutes < 1 || visitorTimeoutMinutes > 1440)
|
||
throw new IllegalArgumentException();
|
||
preferences.edit().putInt("tracking_confirm_ms", confirmationMs).putInt("tracking_lost_ms", lostMs)
|
||
.putInt("tracking_fps", trackingFps)
|
||
.putInt("visitor_session_timeout_minutes", visitorTimeoutMinutes)
|
||
.putInt("reid_similarity_percent", threshold).apply();
|
||
dialog.dismiss();
|
||
} catch (IllegalArgumentException error) {
|
||
Toast.makeText(this, "Confirmation 0–10000 ms, lost 1000–120000 ms, FPS 1–15, session timeout 1–1440 min, Re-ID 1–100%",
|
||
Toast.LENGTH_LONG).show();
|
||
}
|
||
}));
|
||
form.requestFocus();
|
||
dialog.show();
|
||
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
|
||
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
|
||
}
|
||
|
||
private EditText trackingField(LinearLayout form, String label, String key, int fallback, String explanation) {
|
||
TextView heading = trackingSettingLabel(form, label);
|
||
EditText field = new EditText(this);
|
||
field.setId(View.generateViewId());
|
||
heading.setLabelFor(field.getId());
|
||
field.setInputType(android.text.InputType.TYPE_CLASS_NUMBER);
|
||
field.setImeOptions(android.view.inputmethod.EditorInfo.IME_ACTION_DONE |
|
||
android.view.inputmethod.EditorInfo.IME_FLAG_NO_EXTRACT_UI);
|
||
field.setText(Integer.toString(preferences.getInt(key, fallback)));
|
||
form.addView(field);
|
||
trackingSettingNote(form, explanation);
|
||
return field;
|
||
}
|
||
|
||
private TextView trackingSettingLabel(LinearLayout form, String name) {
|
||
TextView label = text(name, 15);
|
||
label.setTypeface(Typeface.DEFAULT_BOLD);
|
||
label.setPadding(0, 6, 0, 0);
|
||
form.addView(label);
|
||
return label;
|
||
}
|
||
|
||
private void trackingSettingNote(LinearLayout form, String explanation) {
|
||
TextView note = text(explanation, 13);
|
||
note.setTextColor(0xffaebfd1);
|
||
note.setPadding(0, 0, 0, 10);
|
||
form.addView(note);
|
||
}
|
||
|
||
private String appVersion() {
|
||
try {
|
||
return getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
|
||
} catch (PackageManager.NameNotFoundException error) {
|
||
throw new IllegalStateException("Own package metadata is unavailable", error);
|
||
}
|
||
}
|
||
|
||
private LinearLayout column() {
|
||
LinearLayout view = new LinearLayout(this);
|
||
view.setOrientation(LinearLayout.VERTICAL);
|
||
return view;
|
||
}
|
||
|
||
private TextView text(String value, int size) {
|
||
TextView text = new TextView(this);
|
||
text.setText(value);
|
||
text.setTextSize(size);
|
||
text.setTextColor(0xffe5f2fa);
|
||
return text;
|
||
}
|
||
|
||
private Button button(LinearLayout parent, String name, Runnable action) {
|
||
Button view = new Button(this);
|
||
view.setText(name);
|
||
view.setAllCaps(false);
|
||
view.setOnClickListener(v -> action.run());
|
||
parent.addView(view);
|
||
return view;
|
||
}
|
||
|
||
private Spinner setting(LinearLayout parent, String name, String... values) {
|
||
LinearLayout wrapper = column();
|
||
wrapper.addView(text(name, 12));
|
||
Spinner spinner = new Spinner(this);
|
||
spinner.setContentDescription(name);
|
||
choices(spinner, Arrays.asList(values));
|
||
wrapper.addView(spinner);
|
||
parent.addView(wrapper, new LinearLayout.LayoutParams(0, -2, 1));
|
||
return spinner;
|
||
}
|
||
|
||
private void choices(Spinner spinner, List<?> values) {
|
||
ArrayAdapter<Object> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, values.toArray());
|
||
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
|
||
spinner.setAdapter(adapter);
|
||
}
|
||
|
||
private void setStatus(String message) {
|
||
status.setText(message);
|
||
android.util.Log.i("EdgeVision", message);
|
||
}
|
||
|
||
private void setRunning(boolean value) {
|
||
running = value;
|
||
start.setEnabled(!value);
|
||
test.setEnabled(!value && !FaceReId.CONTROLLED_POC);
|
||
stop.setEnabled(value);
|
||
for (Spinner control : new Spinner[]{resolution, interval, detection, classification, provider, threadCount, faceModel, ageModel})
|
||
control.setEnabled(!value);
|
||
}
|
||
|
||
private Settings readSettings() {
|
||
return new Settings(resolution.getSelectedItem().toString(),
|
||
Integer.parseInt(interval.getSelectedItem().toString()),
|
||
Float.parseFloat(detection.getSelectedItem().toString()),
|
||
Float.parseFloat(classification.getSelectedItem().toString()),
|
||
(String) provider.getSelectedItem(), Integer.parseInt(threadCount.getSelectedItem().toString()),
|
||
faceModels.get(faceModel.getSelectedItemPosition()), demographicModels.get(ageModel.getSelectedItemPosition()),
|
||
preferences.getInt("tracking_confirm_ms", 1000), preferences.getInt("tracking_lost_ms", 10000),
|
||
preferences.getInt("tracking_fps", 5));
|
||
}
|
||
|
||
private void requestCamera() {
|
||
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) startCamera();
|
||
else requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
|
||
}
|
||
|
||
private void startCamera() {
|
||
if (running) return;
|
||
Settings selection = readSettings();
|
||
String[] dimensions = selection.resolution.split("×");
|
||
begin(selection, new InternalCamera(this, Integer.parseInt(dimensions[0]), Integer.parseInt(dimensions[1])));
|
||
}
|
||
|
||
private void begin(Settings selection, VideoSource input) {
|
||
setRunning(true);
|
||
cameraStatus.setText(input instanceof InternalCamera ? "Камера · запуск…" : "Камера · тестовое изображение");
|
||
setStatus("Loading model sessions…");
|
||
final long run = ++generation;
|
||
if (FaceReId.CONTROLLED_POC) {
|
||
updatePocStats(0, 0, 0);
|
||
ui.postDelayed(expirePocSessions, 1000);
|
||
}
|
||
nextFrame = 0;
|
||
skipped.set(0);
|
||
inference.execute(() -> {
|
||
tracker.clear();
|
||
if (FaceReId.CONTROLLED_POC) visitorSessions.clear();
|
||
else visitorSessions.releaseTracks();
|
||
visitEvents.clear();
|
||
ui.post(() -> { if (generation == run) trackingLog.setText("Ожидание посетителей"); });
|
||
nextFaceFrame = 0;
|
||
metricsEpoch = 0;
|
||
frameCount = 0;
|
||
aiFps = 0;
|
||
lastCpuAt = 0;
|
||
try {
|
||
load(selection);
|
||
ui.post(() -> {
|
||
if (generation != run) return;
|
||
source = input;
|
||
setStatus("Opening source · " + selection.provider);
|
||
source.start(new VideoSource.Listener() {
|
||
@Override public void frame(Bitmap frame, String size, double fps, long drops) {
|
||
accept(run, selection, frame, size, fps, drops);
|
||
}
|
||
@Override public void error(String reason) { failed(run, reason); }
|
||
});
|
||
});
|
||
} catch (Exception | LinkageError error) { failed(run, error.toString()); }
|
||
});
|
||
}
|
||
|
||
private void load(Settings config) throws Exception {
|
||
if (loaded != null && loaded.sameModels(config)) { loadMs = 0; return; }
|
||
long startAt = System.nanoTime();
|
||
engine.close();
|
||
loaded = null;
|
||
if (!"yunet".equals(config.face.json.getString("adapter")) || !"cydral-age".equals(config.age.json.getString("adapter")))
|
||
throw new IllegalArgumentException("Unknown model adapter");
|
||
try {
|
||
detector = new YuNet(engine.load(config.face, config.provider, config.threads), config.face);
|
||
ModelRegistry.Entry gender = registry.list("gender").get(0);
|
||
demographics = new CydralDemographics(
|
||
new CydralDemographics.Predictor(engine.load(config.age, "CPU", config.threads), config.age),
|
||
new CydralDemographics.Predictor(engine.load(gender, "CPU", config.threads), gender));
|
||
ModelRegistry.Entry person = registry.list("person").get(0);
|
||
personDetector = new NanoDetPerson(engine.load(person, "CPU", config.threads), person);
|
||
FaceReId.load(reId, registry, engine, config.threads);
|
||
loaded = config;
|
||
loadMs = ms(startAt);
|
||
} catch (Exception failure) {
|
||
engine.close();
|
||
throw failure;
|
||
}
|
||
}
|
||
|
||
private void accept(long run, Settings config, Bitmap bitmap, String size, double fps, long sourceDrops) {
|
||
if (generation != run) return;
|
||
previewFrame = bitmap;
|
||
if (previewQueued.compareAndSet(false, true)) ui.post(() -> {
|
||
previewQueued.set(false);
|
||
if (generation == run) preview.invalidate();
|
||
});
|
||
long now = SystemClock.elapsedRealtime();
|
||
if (now < nextFrame || !busy.compareAndSet(false, true)) { skipped.incrementAndGet(); return; }
|
||
long period = Math.round(1000f / config.trackingFps);
|
||
nextFrame = Math.max(nextFrame + period, now + period / 2);
|
||
inference.execute(() -> {
|
||
try {
|
||
if (generation == run) analyze(run, config, bitmap, size, fps, sourceDrops, now);
|
||
} catch (Exception error) { failed(run, error.toString()); }
|
||
finally { busy.set(false); }
|
||
});
|
||
}
|
||
|
||
private void analyze(long run, Settings config, Bitmap frame, String size, double cameraFps,
|
||
long sourceDrops, long now) throws Exception {
|
||
long inferenceAt = System.nanoTime();
|
||
List<PersonTracker.Detection> people = personDetector.detect(frame);
|
||
List<PersonTracker.Event> events = tracker.update(people, now, config.confirmMs, config.lostMs);
|
||
double trackingMs = ms(inferenceAt);
|
||
int visitorTimeoutMinutes = visitorTimeoutMinutes();
|
||
FaceReId.setThreshold(reId, preferences.getInt("reid_similarity_percent", DEFAULT_REID_THRESHOLD) / 100f);
|
||
visitorSessions.expire(now, visitorTimeoutMinutes * 60000L);
|
||
for (PersonTracker.Event event : events) {
|
||
if (event.state == PersonTracker.State.TEMPORARILY_LOST) visitorSessions.temporarilyLost(event.track.id);
|
||
if (event.state == PersonTracker.State.CLOSED) visitorSessions.trackClosed(event.track.id);
|
||
}
|
||
boolean changed = false;
|
||
for (PersonTracker.Event event : events) {
|
||
String message;
|
||
switch (event.state) {
|
||
case ACTIVE:
|
||
if (event.previous == PersonTracker.State.TEMPORARILY_LOST) {
|
||
message = "Трек восстановлен. Впервые обнаружен " + durationAgo(now - event.track.firstSeen) +
|
||
" назад, последнее наблюдение " + durationAgo(now - event.previousSeen) +
|
||
" назад. Движение и положение совпали. Прежний ID сохранён.";
|
||
} else {
|
||
totals.countVisit(event.track.analytics);
|
||
changed = true;
|
||
message = "Трек подтверждён. Наблюдение длилось " + durationAgo(now - event.track.confirmationStart) + ".";
|
||
}
|
||
break;
|
||
case DETECTED: message = "Человек обнаружен. Создан предварительный трек."; break;
|
||
case PENDING: message = "Проверяем, что человек остаётся в кадре. Подтверждение — " + durationAgo(config.confirmMs) + "."; break;
|
||
case TEMPORARILY_LOST: message = "Человек временно вне зоны детекции. ID сохраняется до " + durationAgo(config.lostMs) + " от последнего наблюдения."; break;
|
||
case CLOSED: message = "Последнее наблюдение " + durationAgo(now - event.previousSeen) + " назад. Таймаут истёк, трек закрыт."; break;
|
||
default: throw new IllegalStateException("Unknown track state");
|
||
}
|
||
addVisitEvent("#" + event.track.id + " · " + message);
|
||
}
|
||
|
||
double faceMs = -1, ageMs = -1;
|
||
int faceCount = 0;
|
||
List<DrawBox> overlays = new ArrayList<>();
|
||
Map<PersonTracker.Track, Face> assignments = Collections.emptyMap();
|
||
if (now >= nextFaceFrame && tracker.count(PersonTracker.State.ACTIVE) > 0) {
|
||
nextFaceFrame = now + config.interval;
|
||
long faceAt = System.nanoTime();
|
||
List<Face> faces = detector.detect(frame, config.detection);
|
||
faceMs = ms(faceAt);
|
||
faceCount = faces.size();
|
||
long ageAt = System.nanoTime();
|
||
long runs = demographics.runs();
|
||
assignments = associateFaces(faces);
|
||
for (Map.Entry<PersonTracker.Track, Face> entry : assignments.entrySet()) {
|
||
VisitorAnalytics analytics = entry.getKey().analytics;
|
||
Face face = entry.getValue();
|
||
if (analytics.needsClassification(now)) {
|
||
Demographics estimate = demographics.classify(frame, face);
|
||
analytics.sample(demographics.age(estimate), demographics.gender(estimate, config.classification),
|
||
estimate.confidence, now);
|
||
changed |= totals.observe(analytics);
|
||
}
|
||
overlays.add(new DrawBox(face.box, "Face #" + entry.getKey().id));
|
||
}
|
||
if (demographics.runs() != runs) ageMs = ms(ageAt);
|
||
}
|
||
// Returning tracks already bound to a session keep priority over new observations.
|
||
for (PersonTracker.Track track : tracker.tracks()) {
|
||
if (track.state == PersonTracker.State.ACTIVE) visitorSessions.reserveObservedTrack(track.id);
|
||
}
|
||
for (PersonTracker.Track track : tracker.tracks()) {
|
||
if (track.state != PersonTracker.State.ACTIVE) continue;
|
||
float[] sample = visitorSessions.needsObservation(track.id) ?
|
||
FaceReId.embed(reId, frame, assignments.get(track)) : null;
|
||
boolean awaitMoreEvidence = FaceReId.CONTROLLED_POC &&
|
||
now - track.activeSince < 5000L;
|
||
VisitorSessions.Assignment assignment;
|
||
try {
|
||
assignment = visitorSessions.observe(track.id, now, sample, awaitMoreEvidence);
|
||
} finally {
|
||
if (sample != null) Arrays.fill(sample, 0);
|
||
}
|
||
switch (assignment.kind) {
|
||
case RECONNECTED:
|
||
addVisitEvent("#" + track.id + " · Повторное обнаружение. Сессия V" +
|
||
assignment.visitorId + " продлена. Unique Visitors без изменений.");
|
||
break;
|
||
case UNCERTAIN:
|
||
addVisitEvent("#" + track.id + " · Сопоставление неопределённое. Unique Visitors без изменений.");
|
||
break;
|
||
case CREATED:
|
||
addVisitEvent("#" + track.id + " · Открыта сессия V" + assignment.visitorId +
|
||
(FaceReId.CONTROLLED_POC ? ". Новая запись в оценке." : ". Re-ID отключён."));
|
||
break;
|
||
default: break;
|
||
}
|
||
}
|
||
|
||
for (PersonTracker.Track track : tracker.tracks()) {
|
||
if (track.state == PersonTracker.State.TEMPORARILY_LOST) continue;
|
||
PersonTracker.Box box = track.box;
|
||
overlays.add(new DrawBox(new RectF(box.left, box.top, box.right, box.bottom),
|
||
"#" + track.id + " " + (track.confirmed ? track.analytics.label() : "Pending")));
|
||
}
|
||
int activeTracks = tracker.count(PersonTracker.State.ACTIVE);
|
||
if (generation != run) return;
|
||
if (changed) persist();
|
||
double totalMs = ms(inferenceAt);
|
||
long current = SystemClock.elapsedRealtime();
|
||
if (metricsEpoch == 0) metricsEpoch = current;
|
||
frameCount++;
|
||
boolean sampled = current - metricsEpoch >= 1000;
|
||
if (sampled) {
|
||
aiFps = 1000.0 * frameCount / (current - metricsEpoch);
|
||
metricsEpoch = current;
|
||
frameCount = 0;
|
||
}
|
||
int visits = totals.visits;
|
||
int[] genders = totals.genders.clone(), ages = totals.ages.clone();
|
||
long unique = visitorSessions.totalCreated(), repeated = visitorSessions.repeatedCount();
|
||
int openSessions = visitorSessions.openCount();
|
||
final String tracking = visitEvents.isEmpty() ? "Ожидание посетителей" : String.join("\n\n", visitEvents);
|
||
final JSONObject detail;
|
||
if (sampled) {
|
||
JSONObject report = metrics(config, size, cameraFps, faceMs, ageMs, totalMs, sourceDrops, faceCount, trackingMs, visitorTimeoutMinutes);
|
||
benchmark.add(report);
|
||
detail = report;
|
||
android.util.Log.i("EdgeVisionBench", report.toString());
|
||
} else detail = null;
|
||
ui.post(() -> {
|
||
if (generation != run) return;
|
||
status.setText("Source active · adult estimates");
|
||
if (!tracking.contentEquals(trackingLog.getText())) trackingLog.setText(tracking);
|
||
preview.boxes = overlays;
|
||
preview.invalidate();
|
||
updateStats(activeTracks, visits, genders, ages);
|
||
updatePocStats(unique, repeated, openSessions);
|
||
if (detail != null) {
|
||
diagnostics.update(detail);
|
||
if (source instanceof InternalCamera) {
|
||
double fps = detail.optDouble("camera_fps");
|
||
String rate = Double.isNaN(fps) ? "измеряем FPS…" :
|
||
String.format(Locale.getDefault(), "%.1f FPS", fps);
|
||
cameraStatus.setText("Камера · " + size + " · " + rate);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
private Map<PersonTracker.Track, Face> associateFaces(List<Face> faces) {
|
||
Map<PersonTracker.Track, Face> result = new LinkedHashMap<>();
|
||
for (Face face : faces) {
|
||
PersonTracker.Track best = null;
|
||
double bestScore = -1, runnerUp = -1;
|
||
for (PersonTracker.Track track : tracker.tracks()) {
|
||
if (track.state != PersonTracker.State.ACTIVE) continue;
|
||
PersonTracker.Box box = track.box;
|
||
float x = face.box.centerX(), y = face.box.centerY();
|
||
if (x < box.left || x > box.right || y < box.top - .03f ||
|
||
y > box.top + .58f * box.height()) continue;
|
||
double score = 1 - Math.abs(x - box.x()) / box.width()
|
||
- Math.abs(y - (box.top + .18f * box.height())) / box.height();
|
||
if (score > bestScore) {
|
||
runnerUp = bestScore;
|
||
bestScore = score;
|
||
best = track;
|
||
} else runnerUp = Math.max(runnerUp, score);
|
||
}
|
||
if (best == null || bestScore - runnerUp < .12) continue;
|
||
Face previous = result.get(best);
|
||
if (previous == null || face.confidence > previous.confidence) result.put(best, face);
|
||
}
|
||
return result;
|
||
}
|
||
|
||
private JSONObject metrics(Settings config, String size, double cameraFps, double faceMs, double ageMs,
|
||
double totalMs, long sourceDrops, int faces, double trackingMs, int visitorTimeoutMinutes) throws Exception {
|
||
long now = SystemClock.elapsedRealtime(), cpu = android.os.Process.getElapsedCpuTime();
|
||
Object cpuPercent = lastCpuAt == 0 ? JSONObject.NULL : round(100.0 * (cpu - lastCpu) / Math.max(1, now - lastCpuAt));
|
||
lastCpuAt = now;
|
||
lastCpu = cpu;
|
||
return new JSONObject()
|
||
.put("runtime", "ONNX Runtime 1.32.0").put("provider", config.provider).put("threads", config.threads)
|
||
.put("detector", config.face.toString()).put("demographics", config.age + " / Cydral Gender v1")
|
||
.put("detector_nodes", detector.session.providerAssignment())
|
||
.put("demographics_nodes", demographics.providerAssignment())
|
||
.put("resolution", size).put("camera_fps", cameraFps <= 0 ? JSONObject.NULL : round(cameraFps))
|
||
.put("inference_fps", round(aiFps)).put("detection_ms", faceMs < 0 ? JSONObject.NULL : round(faceMs))
|
||
.put("person_detector", "NanoDet-Plus 256").put("person_nodes", personDetector.session.providerAssignment())
|
||
.put("tracking_fps", round(aiFps)).put("tracking_ms", round(trackingMs))
|
||
.put("active_tracks", tracker.count(PersonTracker.State.ACTIVE))
|
||
.put("lost_tracks", tracker.count(PersonTracker.State.TEMPORARILY_LOST))
|
||
.put("lost_events", tracker.lostEvents).put("restored_tracks", tracker.restored)
|
||
.put("created_tracks", tracker.created).put("closed_tracks", tracker.closed)
|
||
.put("total_visits", totals.visits).put("id_switches", JSONObject.NULL)
|
||
.put("average_dwell_s", tracker.averageDwellSeconds())
|
||
.put("tracking_target_fps", config.trackingFps).put("confirmation_ms", config.confirmMs)
|
||
.put("lost_timeout_ms", config.lostMs)
|
||
.put("visitor_session_timeout_minutes", visitorTimeoutMinutes)
|
||
.put("open_visitor_sessions", visitorSessions.openCount())
|
||
.put("created_visitor_sessions", visitorSessions.totalCreated())
|
||
.put("reid_status", visitorSessions.matchingEnabled() ? "SFace PoC" : "Disabled")
|
||
.put("repeated_detections", visitorSessions.repeatedCount())
|
||
.put("uncertain_matches", visitorSessions.uncertainCount())
|
||
.put("age_gender_ms", ageMs < 0 ? JSONObject.NULL : round(ageMs))
|
||
.put("total_ms", round(totalMs)).put("session_load_ms", round(loadMs)).put("interval_ms", config.interval)
|
||
.put("cpu_pct", cpuPercent).put("pss_mib", round(Debug.getPss() / 1024.0)).put("cpu_temperature_c", JSONObject.NULL)
|
||
.put("frame_drops", sourceDrops + skipped.get()).put("errors", errors)
|
||
.put("faces", faces).put("uptime_s", (now - startedAt) / 1000);
|
||
}
|
||
|
||
private static double ms(long start) { return (System.nanoTime() - start) / 1e6; }
|
||
private static double round(double value) { return Math.round(value * 10) / 10.0; }
|
||
|
||
private void updateStats(int current, int visits, int[] genders, int[] ages) {
|
||
String value = Integer.toString(current);
|
||
if (!value.contentEquals(currentVisitorValue.getText())) currentVisitorValue.setText(value);
|
||
diagnostics.updateConfirmedTracks(visits, genders, ages);
|
||
}
|
||
|
||
private void failed(long run, String reason) {
|
||
android.util.Log.e("EdgeVision", reason);
|
||
inference.execute(() -> errors++);
|
||
ui.post(() -> { if (generation == run) halt(reason + " · select CPU to retry"); });
|
||
}
|
||
|
||
private void addVisitEvent(String event) {
|
||
if (visitEvents.size() == 30) visitEvents.removeLast();
|
||
visitEvents.addFirst("[" + eventClock.format(new Date()) + "] " + event);
|
||
}
|
||
|
||
private static String durationAgo(long millis) {
|
||
long seconds = Math.max(0, millis) / 1000;
|
||
if (seconds == 0) return millis + " мс";
|
||
if (seconds < 60) return seconds + " с";
|
||
return seconds / 60 + " мин " + seconds % 60 + " с";
|
||
}
|
||
|
||
private void reset() {
|
||
inference.execute(() -> {
|
||
tracker.clear();
|
||
visitorSessions.clear();
|
||
visitEvents.clear();
|
||
totals.reset();
|
||
persist();
|
||
ui.post(() -> {
|
||
preview.boxes = java.util.Collections.emptyList();
|
||
preview.invalidate();
|
||
trackingLog.setText("Журнал очищен");
|
||
updateStats(0, 0, new int[3], new int[7]);
|
||
updatePocStats(0, 0, 0);
|
||
});
|
||
});
|
||
}
|
||
|
||
private int visitorTimeoutMinutes() {
|
||
return preferences.getInt("visitor_session_timeout_minutes", VisitorSessions.DEFAULT_TIMEOUT_MINUTES);
|
||
}
|
||
|
||
private void expirePocSessions() {
|
||
long run = generation;
|
||
inference.execute(() -> {
|
||
if (generation != run) return;
|
||
visitorSessions.expire(SystemClock.elapsedRealtime(), visitorTimeoutMinutes() * 60000L);
|
||
long unique = visitorSessions.totalCreated(), repeated = visitorSessions.repeatedCount();
|
||
int count = visitorSessions.openCount();
|
||
ui.post(() -> {
|
||
if (generation != run || !running) return;
|
||
updatePocStats(unique, repeated, count);
|
||
ui.postDelayed(expirePocSessions, 1000);
|
||
});
|
||
});
|
||
}
|
||
|
||
private void halt(String message) {
|
||
long stoppedRun = ++generation;
|
||
ui.removeCallbacks(expirePocSessions);
|
||
if (source != null) {
|
||
source.close();
|
||
source = null;
|
||
}
|
||
previewFrame = null;
|
||
preview.boxes = java.util.Collections.emptyList();
|
||
preview.invalidate();
|
||
setRunning(false);
|
||
cameraStatus.setText("Камера · остановлена");
|
||
setStatus(message);
|
||
inference.execute(() -> {
|
||
if (FaceReId.CONTROLLED_POC) visitorSessions.closeSessions();
|
||
else visitorSessions.releaseTracks();
|
||
long unique = visitorSessions.totalCreated(), repeated = visitorSessions.repeatedCount();
|
||
int visits = totals.visits;
|
||
int[] genders = totals.genders.clone(), ages = totals.ages.clone();
|
||
ui.post(() -> {
|
||
if (generation != stoppedRun) return;
|
||
updateStats(0, visits, genders, ages);
|
||
updatePocStats(unique, repeated, 0);
|
||
});
|
||
});
|
||
}
|
||
|
||
@Override public void onRequestPermissionsResult(int request, String[] permissions, int[] grants) {
|
||
super.onRequestPermissionsResult(request, permissions, grants);
|
||
if (request == 1 && grants.length > 0 && grants[0] == PackageManager.PERMISSION_GRANTED) {
|
||
configureSizes();
|
||
startCamera();
|
||
} else if (request == 1) setStatus("Camera permission denied");
|
||
}
|
||
|
||
@Override protected void onActivityResult(int request, int code, Intent data) {
|
||
super.onActivityResult(request, code, data);
|
||
if (code != RESULT_OK || data == null || data.getData() == null) return;
|
||
android.net.Uri uri = data.getData();
|
||
if (request != 2 || FaceReId.CONTROLLED_POC) return;
|
||
begin(readSettings(), new VideoSource() {
|
||
private boolean closed;
|
||
private final Runnable cleanup = () -> closed = true;
|
||
@Override public void start(Listener listener) {
|
||
inference.execute(() -> {
|
||
try {
|
||
android.graphics.ImageDecoder.Source image = ImageDecoder.createSource(getContentResolver(), uri);
|
||
Bitmap bitmap = ImageDecoder.decodeBitmap(image, (decoder, info, item) -> {
|
||
decoder.setAllocator(ImageDecoder.ALLOCATOR_SOFTWARE);
|
||
int width = info.getSize().getWidth(), height = info.getSize().getHeight();
|
||
float scale = Math.min(1, 960f / Math.max(width, height));
|
||
decoder.setTargetSize(Math.max(1, Math.round(width * scale)), Math.max(1, Math.round(height * scale)));
|
||
});
|
||
ui.post(new Runnable() {
|
||
@Override public void run() {
|
||
if (closed) return;
|
||
listener.frame(bitmap, "Test " + bitmap.getWidth() + "×" + bitmap.getHeight(), 0, 0);
|
||
ui.postDelayed(this, 100);
|
||
}
|
||
});
|
||
} catch (Exception failure) { listener.error(failure.toString()); }
|
||
});
|
||
}
|
||
@Override public void close() { cleanup.run(); }
|
||
});
|
||
}
|
||
|
||
@Override protected void onStart() {
|
||
super.onStart();
|
||
resources.start();
|
||
}
|
||
|
||
@Override protected void onStop() {
|
||
resources.stop();
|
||
if (running) halt("Stopped in background");
|
||
super.onStop();
|
||
}
|
||
|
||
@Override protected void onDestroy() {
|
||
if (engine != null) inference.execute(engine::close);
|
||
inference.shutdown();
|
||
super.onDestroy();
|
||
}
|
||
|
||
private static final class Settings {
|
||
final String resolution, provider;
|
||
final int interval, threads;
|
||
final int confirmMs, lostMs, trackingFps;
|
||
final float detection, classification;
|
||
final ModelRegistry.Entry face, age;
|
||
Settings(String resolution, int interval, float detection, float classification, String provider,
|
||
int threads, ModelRegistry.Entry face, ModelRegistry.Entry age, int confirmMs, int lostMs, int trackingFps) {
|
||
this.resolution = resolution;
|
||
this.interval = interval;
|
||
this.detection = detection;
|
||
this.classification = classification;
|
||
this.provider = provider;
|
||
this.threads = threads;
|
||
this.face = face;
|
||
this.age = age;
|
||
this.confirmMs = confirmMs;
|
||
this.lostMs = lostMs;
|
||
this.trackingFps = trackingFps;
|
||
}
|
||
boolean sameModels(Settings other) {
|
||
return other.face == face && other.age == age && other.provider.equals(provider) && other.threads == threads;
|
||
}
|
||
}
|
||
|
||
private static final class DrawBox {
|
||
final RectF rect;
|
||
final String label;
|
||
DrawBox(RectF rect, String label) { this.rect = rect; this.label = label; }
|
||
}
|
||
|
||
private final class Preview extends View {
|
||
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
|
||
List<DrawBox> boxes = java.util.Collections.emptyList();
|
||
Preview() { super(MainActivity.this); }
|
||
@Override protected void onDraw(Canvas canvas) {
|
||
canvas.drawColor(0xff080d12);
|
||
Bitmap frame = previewFrame;
|
||
if (frame == null) return;
|
||
float scale = Math.min(getWidth() / (float) frame.getWidth(), getHeight() / (float) frame.getHeight());
|
||
float width = scale * frame.getWidth(), height = scale * frame.getHeight();
|
||
float x = (getWidth() - width) / 2, y = (getHeight() - height) / 2;
|
||
paint.setColor(Color.WHITE);
|
||
paint.setStyle(Paint.Style.FILL);
|
||
canvas.drawBitmap(frame, null, new RectF(x, y, x + width, y + height), paint);
|
||
for (DrawBox box : boxes) {
|
||
RectF rect = box.rect;
|
||
RectF target = new RectF(x + rect.left * width, y + rect.top * height,
|
||
x + rect.right * width, y + rect.bottom * height);
|
||
paint.setColor(0xff68e2bf);
|
||
paint.setStrokeWidth(2);
|
||
paint.setStyle(Paint.Style.STROKE);
|
||
canvas.drawRect(target, paint);
|
||
paint.setStyle(Paint.Style.FILL);
|
||
paint.setTextSize(17);
|
||
float top = Math.max(y + 20, target.top);
|
||
paint.setColor(0xff0d212c);
|
||
canvas.drawRect(target.left, top - 20, target.left + paint.measureText(box.label) + 8, top + 2, paint);
|
||
paint.setColor(Color.WHITE);
|
||
canvas.drawText(box.label, target.left + 3, top - 3, paint);
|
||
}
|
||
}
|
||
}
|
||
}
|