[Feat] (Android plugin, renderer samples): add interactive tests and external trace replay

This commit is contained in:
BZLZHH committed 2026-11-29 11:10:39 +08:00
1 parent 9560cca571
commit 04f7faedc1
17 files changed
+2328 -30

No files matched your search

@@ -86,6 +86,15 @@
android:exported="false"
android:process=":bench" />
<activity
android:name=".TestActivity"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|uiMode"
android:exported="false" />
<service
android:name=".TestService"
android:exported="false"
android:process=":test" />
<meta-data
android:name="fclPlugin_V2"
android:resource="@string/config" />
@@ -0,0 +1,176 @@
package top.mobilegl.plugin;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
final class EnvironmentOptions {
private static final String INHERIT = "Inherit";
private static final String UNSET = "Unset";
private static final String CUSTOM = "Custom value…";
private final Activity activity;
private final Runnable changed;
private final List<Option> catalog = new ArrayList<>();
private final Bundle overrides = new Bundle();
EnvironmentOptions(Activity activity, Runnable changed) {
this.activity = activity;
this.changed = changed;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
activity.getAssets().open("test-environment.tsv"), StandardCharsets.UTF_8))) {
for (String line; (line = reader.readLine()) != null;) {
int tab = line.indexOf(' ');
if (tab >= 0) catalog.add(new Option(line.substring(0, tab), line.substring(tab + 1)));
}
} catch (IOException ignored) {
catalog.clear();
}
}
Bundle snapshot() {
return new Bundle(overrides);
}
void restore(Bundle state) {
if (state != null) overrides.putAll(state);
}
void show() {
if (catalog.isEmpty()) {
new AlertDialog.Builder(activity).setMessage("Environment options unavailable")
.setPositiveButton("Close", null).show();
return;
}
LinearLayout panel = new LinearLayout(activity);
panel.setOrientation(LinearLayout.VERTICAL);
SearchView search = new SearchView(activity);
search.setQueryHint("Search variables");
panel.addView(search);
ListView list = new ListView(activity);
int listHeight = activity.getResources().getDisplayMetrics().heightPixels / 2;
panel.addView(list, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, listHeight));
List<Option> visible = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<>(activity, android.R.layout.simple_list_item_1);
list.setAdapter(adapter);
Runnable refresh = () -> {
String query = search.getQuery().toString().trim().toUpperCase(Locale.ROOT);
visible.clear();
adapter.setNotifyOnChange(false);
adapter.clear();
for (Option option : catalog) {
if (!option.name.contains(query)) continue;
visible.add(option);
adapter.add(option.name + "\n" + state(option));
}
adapter.notifyDataSetChanged();
};
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override public boolean onQueryTextSubmit(String query) { return false; }
@Override public boolean onQueryTextChange(String query) {
refresh.run();
return true;
}
});
list.setOnItemClickListener((parent, view, position, id) -> edit(visible.get(position), refresh));
refresh.run();
new AlertDialog.Builder(activity).setTitle("Environment").setView(panel)
.setPositiveButton("Done", null).show();
}
private String state(Option option) {
if (!overrides.containsKey(option.name)) return INHERIT;
String value = overrides.getString(option.name);
if (value == null) return UNSET;
if (option.name.endsWith("_TOKEN")) return "Set";
if (value.isEmpty()) return "Empty value";
int index = option.values.indexOf(value);
return index < 0 ? value : option.labels.get(index);
}
private void edit(Option option, Runnable refresh) {
List<String> labels = new ArrayList<>();
labels.add(INHERIT);
labels.add(UNSET);
labels.addAll(option.labels);
labels.add(CUSTOM);
String value = overrides.getString(option.name);
int current = !overrides.containsKey(option.name) ? 0 : value == null ? 1 : option.values.indexOf(value) + 2;
if (current == 1 && value != null) current = labels.size() - 1;
new AlertDialog.Builder(activity).setTitle(option.name)
.setSingleChoiceItems(labels.toArray(new String[0]), current, (dialog, position) -> {
dialog.dismiss();
if (position == 0) overrides.remove(option.name);
else if (position == 1) overrides.putString(option.name, null);
else if (position == labels.size() - 1) {
editValue(option, refresh, value);
return;
} else overrides.putString(option.name, option.values.get(position - 2));
updated(refresh);
}).setNegativeButton("Cancel", null).show();
}
private void editValue(Option option, Runnable refresh, String current) {
EditText value = new EditText(activity);
value.setSingleLine();
value.setHint("Value");
value.setInputType(option.numeric ? InputType.TYPE_CLASS_NUMBER
: InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
value.setText(current);
AlertDialog dialog = new AlertDialog.Builder(activity).setTitle(option.name).setView(value)
.setNegativeButton("Cancel", null).setPositiveButton("Set", (ignored, position) -> {
overrides.putString(option.name, value.getText().toString());
updated(refresh);
}).show();
Runnable validate = () -> {
String text = value.getText().toString();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(text.length() <= 4096 && text.indexOf(0) < 0);
};
value.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { validate.run(); }
@Override public void afterTextChanged(Editable s) {}
});
validate.run();
}
private void updated(Runnable refresh) {
refresh.run();
changed.run();
}
private static final class Option {
final String name;
final boolean numeric;
final List<String> labels = new ArrayList<>();
final List<String> values = new ArrayList<>();
Option(String name, String type) {
this.name = name;
numeric = type.equals("number");
if (type.isEmpty() || numeric) return;
for (String choice : type.split("[|]")) {
int equals = choice.indexOf('=');
labels.add(equals < 0 ? choice : choice.substring(0, equals));
values.add(equals < 0 ? choice : choice.substring(equals + 1));
}
}
}
}
@@ -10,13 +10,12 @@ import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Bottom navigation bar switching between the POST screen and the render server
* control screen. Tabs switch by reordering the other activity to the front, so each
* screen keeps its state while the other is open.
* Bottom navigation bar. Tabs reorder their activities to the front to preserve screen state.
*/
public final class NavBar {
public static final int TAB_POST = 0;
public static final int TAB_SERVER = 1;
public static final int TAB_TEST = 2;
private static final int COLOR_BAR = 0xFF1E1E1E;
private static final int COLOR_TAB_ACTIVE = 0xFFEEEEEE;
@@ -37,6 +36,7 @@ public final class NavBar {
bar.setBackgroundColor(COLOR_BAR);
addTab(activity, bar, "Diagnostics", PostActivity.class, currentTab == TAB_POST);
addTab(activity, bar, "Server", ServerControlActivity.class, currentTab == TAB_SERVER);
addTab(activity, bar, "Test", TestActivity.class, currentTab == TAB_TEST);
root.addView(bar, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, dp(activity, BAR_HEIGHT_DP)));
return root;
@@ -0,0 +1,418 @@
package top.mobilegl.plugin;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public final class TestActivity extends Activity {
private static final int PICK_TRACE = 1;
private static native String nativeSampleCatalog();
private final Handler main = new Handler(Looper.getMainLooper());
private final ArrayList<String> samples = new ArrayList<>();
private Spinner sample;
private Button environment;
private EnvironmentOptions environmentOptions;
private Button run;
private Button replayTrace;
private Switch vsync;
private SurfaceView preview;
private ImageView snapshot;
private String snapshotPath;
private static final int FRAME_WIDTH = 1280;
private static final int FRAME_HEIGHT = 720;
private TextView report;
private String result;
private Run active;
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
ScrollView scroll = new ScrollView(this);
scroll.setBackgroundColor(0xFF121212);
LinearLayout content = new LinearLayout(this);
content.setOrientation(LinearLayout.VERTICAL);
int padding = dp(16);
content.setPadding(padding, padding, padding, padding);
scroll.addView(content);
setContentView(NavBar.wrap(this, scroll, NavBar.TAB_TEST));
TextView title = text("MobileGL Test", 20);
title.setTypeface(null, Typeface.BOLD);
content.addView(title);
content.addView(text("Scene", 14));
sample = new Spinner(this);
sample.setContentDescription("Scene");
content.addView(sample);
environment = new Button(this);
environmentOptions = new EnvironmentOptions(this, this::updateEnvironmentLabel);
environment.setOnClickListener(view -> environmentOptions.show());
if (state != null) environmentOptions.restore(state.getBundle("environmentOptions"));
updateEnvironmentLabel();
content.addView(environment);
vsync = new Switch(this);
vsync.setText("VSync");
vsync.setChecked(state == null || state.getBoolean("vsync", true));
content.addView(vsync);
run = new Button(this);
run.setText("Run");
run.setOnClickListener(view -> {
if (active == null) startRun();
else active.cancel();
});
content.addView(run);
replayTrace = new Button(this);
replayTrace.setText("Replay trace…");
replayTrace.setOnClickListener(view -> {
if (active == null) chooseTrace();
else if (active.isTrace()) active.cancel();
});
content.addView(replayTrace);
FrameLayout frame = new FrameLayout(this);
content.addView(frame);
preview = new SurfaceView(this) {
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
int width = MeasureSpec.getSize(widthSpec);
setMeasuredDimension(width, width * FRAME_HEIGHT / FRAME_WIDTH);
}
};
preview.setContentDescription("Live sample surface");
frame.addView(preview, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));
snapshot = new ImageView(this);
snapshot.setScaleType(ImageView.ScaleType.FIT_CENTER);
snapshot.setBackgroundColor(0xFF121212);
snapshot.setContentDescription("Trace snapshot");
frame.addView(snapshot, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
showSnapshot(state == null ? null : state.getString("snapshotPath"));
preview.getHolder().setFixedSize(FRAME_WIDTH, FRAME_HEIGHT);
preview.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override public void surfaceCreated(SurfaceHolder holder) {}
@Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
@Override public void surfaceDestroyed(SurfaceHolder holder) {
if (active != null && !active.isTrace() && !active.received) active.cancel();
}
});
report = text("", 14);
report.setTextIsSelectable(true);
content.addView(report);
try {
System.loadLibrary("MobileGL");
JSONArray catalog = new JSONArray(nativeSampleCatalog());
for (int i = 0; i < catalog.length(); i++) samples.add(catalog.getString(i));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, samples);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sample.setAdapter(adapter);
if (state != null) {
sample.setSelection(Math.max(0, samples.indexOf(state.getString("sample"))));
result = state.getString("result");
report.setText(result);
}
} catch (LinkageError | JSONException failure) {
showResult("Samples unavailable: " + failure.getMessage());
}
run.setEnabled(!samples.isEmpty());
}
@Override
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putString("sample", (String) sample.getSelectedItem());
state.putBundle("environmentOptions", environmentOptions.snapshot());
state.putString("result", result);
state.putString("snapshotPath", snapshotPath);
state.putBoolean("vsync", vsync.isChecked());
}
@Override
protected void onDestroy() {
if (active != null) active.complete();
super.onDestroy();
}
private void chooseTrace() {
Intent picker = new Intent(Intent.ACTION_OPEN_DOCUMENT)
.addCategory(Intent.CATEGORY_OPENABLE).setType("*/*")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivityForResult(picker, PICK_TRACE);
} catch (ActivityNotFoundException error) {
showResult("No file picker is available");
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != PICK_TRACE || resultCode != RESULT_OK || active != null) return;
Uri trace = data == null ? null : data.getData();
if (trace == null) {
showResult("No trace file was selected");
return;
}
start(new Run("Trace replay", trace, environmentOptions.snapshot(), false));
}
private void startRun() {
Surface surface = preview.getHolder().getSurface();
if (!surface.isValid()) {
showResult("Surface unavailable");
return;
}
start(new Run((String) sample.getSelectedItem(), null, environmentOptions.snapshot(), vsync.isChecked()));
}
private void start(Run request) {
showSnapshot(null);
active = request;
if (active.bind()) {
setRunning(true);
showResult(request.isTrace() ? "Importing and replaying trace…" : "Running…");
} else {
active = null;
showResult("Test process unavailable");
}
}
private void updateEnvironmentLabel() {
int count = environmentOptions.snapshot().size();
environment.setText(count == 0 ? "Environment" : "Environment (" + count + ")");
}
private void setRunning(boolean running) {
sample.setEnabled(!running);
environment.setEnabled(!running);
vsync.setEnabled(!running);
boolean replaying = running && active.isTrace();
run.setText(running && !replaying ? "Cancel" : "Run");
run.setEnabled(replaying ? false : running || !samples.isEmpty());
replayTrace.setText(replaying ? "Cancel trace replay" : "Replay trace…");
replayTrace.setEnabled(!running || replaying);
}
private final class Run implements ServiceConnection {
private final String name;
private final Uri trace;
private final Bundle overrides;
private final boolean useVsync;
private Messenger worker;
private boolean bound;
private boolean cancelled;
private boolean received;
private final Runnable unavailable = () -> fail("Test process unavailable");
Run(String name, Uri trace, Bundle overrides, boolean useVsync) {
this.name = name;
this.trace = trace;
this.overrides = overrides;
this.useVsync = useVsync;
}
boolean isTrace() {
return trace != null;
}
private Button cancelButton() {
return isTrace() ? replayTrace : run;
}
boolean bind() {
bound = bindService(new Intent(TestActivity.this, TestService.class), this, Context.BIND_AUTO_CREATE);
if (bound) main.postDelayed(unavailable, 10_000);
return bound;
}
@Override
public void onServiceConnected(ComponentName component, IBinder binder) {
if (active != this || worker != null) return;
main.removeCallbacks(unavailable);
worker = new Messenger(binder);
Message request = Message.obtain(null, TestService.RUN);
request.getData().putBundle(TestService.ENVIRONMENT, overrides);
if (isTrace()) {
request.getData().putParcelable(TestService.TRACE_URI, trace);
} else {
Surface surface = preview.getHolder().getSurface();
if (!surface.isValid()) {
fail("Surface unavailable");
return;
}
request.getData().putString(TestService.SAMPLE, name);
request.getData().putBoolean(TestService.VSYNC, useVsync);
request.getData().putParcelable(TestService.SURFACE, surface);
}
request.replyTo = new Messenger(new Handler(Looper.getMainLooper(), this::onResult));
try {
worker.send(request);
} catch (RemoteException error) {
fail("Test process unavailable");
}
}
private boolean onResult(Message message) {
if (message.what != TestService.RESULT || active != this || cancelled) return false;
received = true;
String json = message.getData().getString(TestService.REPORT, "");
if (isTrace()) showTraceReport(json);
else showResult(formatReport(name, json));
cancelButton().setEnabled(false);
return true;
}
@Override
public void onServiceDisconnected(ComponentName component) {
if (active != this) return;
if (!received && !cancelled) showResult(name + "\nTest process exited");
complete();
}
@Override
public void onBindingDied(ComponentName component) {
onServiceDisconnected(component);
}
@Override
public void onNullBinding(ComponentName component) {
fail("Test process unavailable");
}
void cancel() {
cancelled = true;
showResult("Canceled");
if (worker == null) {
complete();
return;
}
cancelButton().setEnabled(false);
try {
worker.send(Message.obtain(null, TestService.CANCEL));
} catch (RemoteException ignored) {
complete();
}
}
private void fail(String detail) {
if (active != this) return;
showResult(detail);
complete();
}
void complete() {
main.removeCallbacks(unavailable);
if (bound) unbindService(this);
bound = false;
if (active != this) return;
active = null;
setRunning(false);
}
}
private static String formatReport(String name, String json) {
try {
JSONObject data = new JSONObject(json);
if (data.has("error")) return name + "\n" + data.getString("error");
String report = String.format(Locale.ROOT, "%s%n%s%n%d frames · %.1f FPS%nMedian %.3f ms · P95 %.3f ms%nGL error 0x%04X",
name, data.getString("renderer"), data.getInt("frames"), data.getDouble("fps"),
data.getDouble("medianFrameMs"), data.getDouble("p95FrameMs"), data.getInt("glError"));
int redundantCalls = data.optInt("redundantCallsPerFrame", -1);
if (redundantCalls >= 0) report += "\nRedundant calls per frame: " + redundantCalls;
return report;
} catch (JSONException error) {
return name + "\nInvalid test report";
}
}
private void showTraceReport(String json) {
try {
JSONObject data = new JSONObject(json);
if (data.has("error")) {
showResult("Trace replay\n" + data.getString("error"));
return;
}
String summary = data.getString("name") + "\n"
+ (data.getBoolean("passed") ? "Replay complete" : "Replay failed")
+ "\n" + data.getString("message");
String resultFile = data.getString("resultPath");
if (!resultFile.isEmpty()) summary += "\nResult: " + resultFile;
showResult(summary);
showSnapshot(data.getString("actualPath"));
} catch (JSONException error) {
showResult("Invalid trace replay report");
}
}
private void showSnapshot(String path) {
Bitmap image = null;
if (path != null && !path.isEmpty()) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inJustDecodeBounds = false;
options.inSampleSize = 1;
while (Math.max(options.outWidth, options.outHeight) / options.inSampleSize > FRAME_WIDTH) {
options.inSampleSize *= 2;
}
image = BitmapFactory.decodeFile(path, options);
}
snapshotPath = image == null ? null : path;
snapshot.setImageBitmap(image);
snapshot.setVisibility(image == null ? View.GONE : View.VISIBLE);
}
private void showResult(String text) {
result = text;
report.setText(text);
}
private TextView text(String value, int size) {
TextView view = new TextView(this);
view.setText(value);
view.setTextSize(size);
view.setPadding(0, dp(8), 0, dp(4));
return view;
}
private int dp(int value) {
return Math.round(value * getResources().getDisplayMetrics().density);
}
}
@@ -0,0 +1,123 @@
package top.mobilegl.plugin;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.Process;
import android.os.RemoteException;
import android.system.Os;
import android.view.Surface;
import org.json.JSONObject;
public final class TestService extends Service {
static final int RUN = 1;
static final int RESULT = 2;
static final int CANCEL = 3;
static final String SAMPLE = "sample";
static final String ENVIRONMENT = "environment";
static final String TRACE_URI = "traceUri";
static final String REPORT = "report";
static final String SURFACE = "surface";
static final String VSYNC = "vsync";
private static final long TIMEOUT_MS = 90_000;
static final String BACKEND_ENV_PRIORITY = "MOBILEGL_TEST_BACKEND_ENV_PRIORITY";
private static native String nativeRunSample(String sample, Surface surface, boolean vsync);
private final Handler main = new Handler(Looper.getMainLooper());
private final Messenger requests = new Messenger(new Handler(Looper.getMainLooper(), this::onRequest));
private boolean started;
private boolean finished;
@Override
public IBinder onBind(Intent intent) {
return requests.getBinder();
}
@Override
public boolean onUnbind(Intent intent) {
if (started) exit();
return false;
}
private boolean onRequest(Message message) {
if (message.what == CANCEL) {
exit();
return true;
}
if (message.what != RUN || started || message.replyTo == null) return false;
started = true;
Messenger reply = message.replyTo;
Bundle args = message.getData();
Uri trace = args.getParcelable(TRACE_URI);
if (trace == null) main.postDelayed(() -> finish(reply, error("Timed out")), TIMEOUT_MS);
new Thread(() -> {
String result;
Surface surface = args.getParcelable(SURFACE);
try {
result = trace == null ? runSample(args, surface)
: TraceTest.run(this, trace, args.getBundle(ENVIRONMENT));
} catch (Exception | LinkageError failure) {
String detail = failure.getMessage();
result = error(detail == null ? failure.getClass().getSimpleName() : detail);
} finally {
if (surface != null) surface.release();
}
String report = result == null ? error("No result") : result;
main.post(() -> finish(reply, report));
}, "MobileGLTest").start();
return true;
}
private static String runSample(Bundle args, Surface surface) throws Exception {
String sample = args.getString(SAMPLE);
if (sample == null || sample.isEmpty()) throw new IllegalArgumentException("Select a sample");
Bundle overrides = args.getBundle(ENVIRONMENT);
if (overrides != null) {
for (String name : overrides.keySet()) {
String value = overrides.getString(name);
if (value == null) Os.unsetenv(name);
else Os.setenv(name, value, true);
}
if (overrides.containsKey(ServerEnvironment.BACKEND)) {
// A Test selection also applies to a renderer process it spawns.
Os.setenv(BACKEND_ENV_PRIORITY, "1", true);
}
}
System.loadLibrary("MobileGL");
if (surface == null || !surface.isValid()) throw new IllegalStateException("Surface unavailable");
return nativeRunSample(sample, surface, args.getBoolean(VSYNC, true));
}
private static String error(String detail) {
return "{\"error\":" + JSONObject.quote(detail) + "}";
}
private void finish(Messenger reply, String report) {
if (finished) return;
finished = true;
main.removeCallbacksAndMessages(null);
Message result = Message.obtain(null, RESULT);
result.getData().putString(REPORT, report);
try {
reply.send(result);
} catch (RemoteException ignored) {
exit();
return;
}
// The client unbinds after reading the report. Exit even if it stops responding.
main.postDelayed(this::exit, 1_000);
}
private void exit() {
TraceTest.discardInput(this);
Process.killProcess(Process.myPid());
}
}
@@ -0,0 +1,118 @@
package top.mobilegl.plugin;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import org.json.JSONObject;
final class TraceTest {
private static final String OUTPUT_DIRECTORY = "test-trace-replay";
private static final String INPUT_FILENAME = "input.trace";
private static final String TRANSPORT = "MOBILEGL_TRANSPORT";
private static final String SERVER_PATH = "MOBILEGL_IPC_SERVER_PATH";
private TraceTest() {}
static String run(Context context, Uri source, Bundle overrides) throws Exception {
if (!"content".equals(source.getScheme())) throw new IOException("Select a document from the file picker");
File output = outputDirectory(context);
Files.createDirectories(output.toPath());
File[] files = output.listFiles();
if (files == null) throw new IOException("Trace output directory unavailable");
for (File file : files) Files.deleteIfExists(file.toPath());
File input = new File(output, INPUT_FILENAME);
try {
copyDocument(context, source, input);
if (overrides == null) overrides = new Bundle();
String backend = overrides.getString(ServerEnvironment.BACKEND);
if (backend == null) backend = context.getString(R.string.mobilegl_default_backend);
System.loadLibrary("trace_replay_runner");
Result result = nativeReplay(input.getAbsolutePath(), output.getAbsolutePath(), backend,
environment(context, overrides));
if (result == null) throw new IOException("Trace replay returned no result");
return new JSONObject().put("name", displayName(context, source)).put("passed", result.passed)
.put("message", result.message).put("actualPath", existingPath(result.actualPath))
.put("resultPath", existingPath(result.resultPath)).toString();
} finally {
discardInput(context);
}
}
private static File outputDirectory(Context context) {
return new File(context.getCacheDir(), OUTPUT_DIRECTORY);
}
static void discardInput(Context context) {
new File(outputDirectory(context), INPUT_FILENAME).delete();
}
private static String existingPath(String path) {
return new File(path).isFile() ? path : "";
}
private static String displayName(Context context, Uri source) {
try (Cursor cursor = context.getContentResolver().query(source,
new String[]{OpenableColumns.DISPLAY_NAME}, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(0);
if (name != null && !name.isEmpty()) return name.substring(0, Math.min(name.length(), 256));
}
} catch (RuntimeException ignored) {
}
return "Trace replay";
}
private static void copyDocument(Context context, Uri source, File input) throws IOException {
// The native parser opens a regular file twice. A document provider can return a pipe.
try (FileOutputStream output = new FileOutputStream(input);
InputStream stream = context.getContentResolver().openInputStream(source)) {
if (stream == null) throw new IOException("Document provider did not open the file");
byte[] buffer = new byte[128 * 1024];
for (int count; (count = stream.read(buffer)) != -1;) output.write(buffer, 0, count);
} catch (IOException | SecurityException failure) {
throw new IOException("Unable to read the selected trace: " + failure.getMessage(), failure);
}
if (input.length() == 0) throw new IOException("The selected trace is empty");
}
private static String[] environment(Context context, Bundle overrides) {
ArrayList<String> entries = new ArrayList<>();
for (String name : overrides.keySet()) {
String value = overrides.getString(name);
entries.add(value == null ? name : name + "=" + value);
}
if (overrides.containsKey(ServerEnvironment.BACKEND)) entries.add(TestService.BACKEND_ENV_PRIORITY + "=1");
if ("spawn".equalsIgnoreCase(overrides.getString(TRANSPORT)) && !overrides.containsKey(SERVER_PATH)) {
File server = new File(context.getApplicationInfo().nativeLibraryDir, "libMobileGLServer.so");
entries.add(SERVER_PATH + "=" + server.getAbsolutePath());
}
return entries.toArray(new String[0]);
}
private static native Result nativeReplay(String input, String output, String backend, String[] environment);
private static final class Result {
final boolean passed;
final String message;
final String actualPath;
final String resultPath;
Result(boolean passed, String message, String actualPath, String resultPath) {
this.passed = passed;
this.message = message;
this.actualPath = actualPath;
this.resultPath = resultPath;
}
}
}
@@ -1,7 +1,9 @@
#include "trace_replay_core.hpp"
#include "apitrace_exit.hpp"
#include "spawn_spike.hpp"
#include "trace_env_overrides.hpp"
#include "trace_parser.hpp"
#include "trace_replay_lease.hpp"
#include <android/native_window.h>
@@ -9,6 +11,7 @@
#include <jni.h>
#include <exception>
#include <memory>
#include <string>
#include <vector>
#include <sys/stat.h>
@@ -84,6 +87,44 @@ public:
}
};
jobject MakeTestResult(JNIEnv* env, const mobilegl_trace::Result& result) {
jclass clazz = env->FindClass("top/mobilegl/plugin/TraceTest$Result");
if (clazz == nullptr) {
return nullptr;
}
jmethodID ctor = env->GetMethodID(clazz, "<init>", "(ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
if (ctor == nullptr) {
return nullptr;
}
jstring message = env->NewStringUTF(result.message.c_str());
jstring actualPath = env->NewStringUTF(result.actualPath.c_str());
jstring resultPath = env->NewStringUTF(result.resultPath.c_str());
return env->NewObject(clazz, ctor, result.passed ? JNI_TRUE : JNI_FALSE, message, actualPath, resultPath);
}
mobilegl_trace::Result RunTestReplay(mobilegl_trace::Request& request) {
long long lastCall = -1;
long long lastFrameEnd = -1;
{
trace::Parser parser;
if (!parser.open(request.tracePath.c_str())) {
return MakeFailureResult(request, mobilegl_trace::STATUS_INVALID_ARGUMENT, "Could not open the trace");
}
while (std::unique_ptr<trace::Call> call{parser.scan_call()}) {
lastCall = call->no;
if (call->flags & trace::CALL_FLAG_END_FRAME) {
lastFrameEnd = call->no;
}
}
}
// Capture before the final presentation. Cleanup calls can destroy the drawable.
request.targetCall = lastFrameEnd >= 0 ? lastFrameEnd : lastCall;
if (request.targetCall < 0) {
return MakeFailureResult(request, mobilegl_trace::STATUS_INVALID_ARGUMENT, "The trace contains no calls");
}
return mobilegl_trace::RunTraceReplay(request);
}
} // namespace
extern "C" JNIEXPORT jobject JNICALL
@@ -216,6 +257,44 @@ Java_top_mobilegl_plugin_trace_TraceReplayActivity_nativeRunTraceReplay(JNIEnv*
return MakeResult(env, result);
}
extern "C" JNIEXPORT jobject JNICALL
Java_top_mobilegl_plugin_TraceTest_nativeReplay(JNIEnv* env, jclass, jstring input, jstring output, jstring backend,
jobjectArray environment) {
mobilegl_trace::TraceReplayLease lease;
if (!lease) {
mobilegl_trace::Result result;
result.message = "Another trace replay is already running in this process";
return MakeTestResult(env, result);
}
mobilegl_trace::Request request;
request.tracePath = ToString(env, input);
request.outputDir = ToString(env, output);
request.backend = ToString(env, backend);
request.usePbuffer = true;
for (jsize i = 0; i < env->GetArrayLength(environment); ++i) {
auto entry = static_cast<jstring>(env->GetObjectArrayElement(environment, i));
request.envOverrides.push_back(ToString(env, entry));
env->DeleteLocalRef(entry);
}
mobilegl_trace::Result result;
try {
result = RunTestReplay(request);
} catch (const MobileGLRetraceExit&) {
result = MakeFailureResult(request, mobilegl_trace::STATUS_RETRACE_FAILED, "Could not read the trace");
} catch (const std::exception& failure) {
result = MakeFailureResult(request, mobilegl_trace::STATUS_RETRACE_FAILED, failure.what());
} catch (...) {
result = MakeFailureResult(request, mobilegl_trace::STATUS_RETRACE_FAILED, "Unexpected trace replay failure");
}
if (!mobilegl_trace::WriteResultJson(request, result) && result.passed) {
result.passed = false;
result.message = "Replay completed but the result could not be written";
}
return MakeTestResult(env, result);
}
// P0 spike A: exec the packaged MobileGLServer stub from this app process and report what
// happened. Deliberately a separate entry point rather than another parameter on the
// replay call - it shares nothing with a replay, and the trace lane must be able to run