[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

+27 -20
View File
@@ -1,19 +1,26 @@
# MobileGL trace replay APK
# MobileGL trace replay on Android
The Android plugin app has two flavor dimensions:
## Replay from the Test page
- `backend`: `espryt` uses `DirectGLES`, `magma` uses `DirectVulkan`.
- `profile`: `plugin` keeps the original FCL plugin APK behavior, `trace` adds the standalone trace runner Activity.
In the Android app, open **Test**, set any **Environment** overrides, and tap **Replay trace…**.
Choose an apitrace file from Android’s file picker. Replay starts after the app copies the document
into its private cache. The Test page shows the snapshot from the last frame boundary, or from
the last call if the trace has no frame boundary. Tap **Cancel trace replay** to stop importing or
replaying. The app keeps the latest trace result and snapshot in its cache.
Useful debug builds:
Both the standard plugin and the trace APK include the replay library. Supply your own trace file.
## Run with adb
The `trace` profile exposes a standalone runner for adb and CI. It uses the `.trace` application
ID suffix. From the repository root, build either debug variant with the installed Gradle:
```sh
./gradlew -p MobileGL/android-plugin :app:assembleEsprytPluginDebug
./gradlew -p MobileGL/android-plugin :app:assembleEsprytTraceDebug
./gradlew -p MobileGL/android-plugin :app:assembleMagmaTraceDebug
gradle -p android-plugin :app:assemblePluginDebug
gradle -p android-plugin :app:assembleTraceDebug
```
The trace profile keeps the existing plugin manifest metadata and adds:
The trace profile exposes the following activity:
```text
action: top.mobilegl.plugin.TRACE_REPLAY
@@ -27,7 +34,7 @@ trace_path absolute path to the apitrace file
golden_path optional absolute path to a golden PNG
output_dir directory for result.json and actual.png
diff_path optional absolute path for a golden-difference PNG
backend DirectGLES or DirectVulkan; defaults to the backend flavor
backend DirectGLES (the default) or DirectVulkan
target_frame target frame index, or -1
target_call target call number, or -1
width optional replay surface width override
@@ -50,7 +57,7 @@ Implementation notes:
- The runner uses a MobileGL-backed EGL window-system shim. GLX calls in PC traces are consumed by apitrace's GLX retrace frontend and mapped onto this EGL shim; the Android runner does not require or call a MobileGL GLX implementation.
- `DirectGLES` and `DirectVulkan` replay on the Activity `SurfaceView` by default. DirectGLES can still use the old offscreen EGL pbuffer path by passing `use_pbuffer=true`.
- Golden comparison is implemented in native C++ with libpng RGBA decode and SSIM validation. The Java Activity only passes arguments and displays the native result, so the replay/compare core is not tied to Android UI or Bitmap APIs and can be ported to Linux.
- The plugin profile still excludes `libtrace_replay_runner.so`; normal plugin APK behavior is preserved.
- The standard plugin exposes replay through its private Test service.
- Set `MOBILEGL_ESPRYT_USE_ANGLE=1` and `MOBILEGL_TRACE_ANGLE_VARIANT=<short-hash>` when running `trace-replay-ci.sh` for DirectGLES. The trace APK contains both allowlisted ANGLE builds with short-hash filenames and SONAMEs; MobileGL resolves its signed native library directory and loads the selected pair by absolute path. Set `MOBILEGL_RETRACE_USE_PBUFFER=1` or pass `--use-pbuffer` to keep DirectGLES offscreen.
Example core-profile trace smoke command for a debug trace APK:
@@ -58,21 +65,21 @@ Example core-profile trace smoke command for a debug trace APK:
```sh
adb push app.trace /data/local/tmp/mobilegl_app.trace
adb push app.golden.png /data/local/tmp/mobilegl_app_ref.png
adb shell run-as top.mobilegl.plugin.espryt.trace mkdir -p files/trace-replay/input files/trace-replay/output
adb shell run-as top.mobilegl.plugin.espryt.trace cp /data/local/tmp/mobilegl_app.trace files/trace-replay/input/app.trace
adb shell run-as top.mobilegl.plugin.espryt.trace cp /data/local/tmp/mobilegl_app_ref.png files/trace-replay/input/app.golden.png
adb shell run-as top.mobilegl.plugin.trace mkdir -p files/trace-replay/input files/trace-replay/output
adb shell run-as top.mobilegl.plugin.trace cp /data/local/tmp/mobilegl_app.trace files/trace-replay/input/app.trace
adb shell run-as top.mobilegl.plugin.trace cp /data/local/tmp/mobilegl_app_ref.png files/trace-replay/input/app.golden.png
adb shell am start -a top.mobilegl.plugin.TRACE_REPLAY \
-n top.mobilegl.plugin.espryt.trace/top.mobilegl.plugin.trace.TraceReplayActivity \
--es trace_path /data/user/0/top.mobilegl.plugin.espryt.trace/files/trace-replay/input/app.trace \
--es golden_path /data/user/0/top.mobilegl.plugin.espryt.trace/files/trace-replay/input/app.golden.png \
--es output_dir /data/user/0/top.mobilegl.plugin.espryt.trace/files/trace-replay/output \
--es diff_path /data/user/0/top.mobilegl.plugin.espryt.trace/files/trace-replay/output/app-diff.png \
-n top.mobilegl.plugin.trace/top.mobilegl.plugin.trace.TraceReplayActivity \
--es trace_path /data/user/0/top.mobilegl.plugin.trace/files/trace-replay/input/app.trace \
--es golden_path /data/user/0/top.mobilegl.plugin.trace/files/trace-replay/input/app.golden.png \
--es output_dir /data/user/0/top.mobilegl.plugin.trace/files/trace-replay/output \
--es diff_path /data/user/0/top.mobilegl.plugin.trace/files/trace-replay/output/app-diff.png \
--es backend DirectGLES \
--ez use_angle true \
--es angle_variant ec889e6ea831 \
--el target_call 31249 \
--es ssim_threshold 0.99
adb shell run-as top.mobilegl.plugin.espryt.trace cat files/trace-replay/output/result.json
adb shell run-as top.mobilegl.plugin.trace cat files/trace-replay/output/result.json
```
## Emulator shards in CI
+43 -6
View File
@@ -126,7 +126,50 @@ val pluginRendererConfig = buildJsonValue {
)
}
val environmentSources = fileTree("../../MobileGL") {
include("**/*.cpp", "**/*.h", "**/*.inc", "**/*.hpp", "**/*.c")
exclude("MG_Test/**", "MG_IntegrationTest/**", "MG_Benchmark/**")
}
val environmentAssets = layout.buildDirectory.dir("generated/testEnvironment/assets")
val generateTestEnvironment = tasks.register("generateTestEnvironment") {
inputs.files(environmentSources)
outputs.dir(environmentAssets)
doLast {
val names = sortedSetOf("LIBGL_ES", "POJAV_RENDERER", "VK_ICD_FILENAMES", "VK_DRIVER_FILES", "VK_LAYER_PATH")
val types = mutableMapOf<String, String>()
val name = Regex(""""(MOBILEGL_[A-Z0-9_]+)"""")
val query = Regex("""QueryEnv(Flag|QuirkOverride|Uint32|MultiDrawMode|GLESMultiDrawMode)\s*\(\s*"(MOBILEGL_[A-Z0-9_]+)"""")
val choices = mapOf(
"Flag" to "Off=0|On=1",
"QuirkOverride" to "Auto|ForceOn|ForceOff",
"Uint32" to "number",
"MultiDrawMode" to "auto|ext|indirect|unroll",
"GLESMultiDrawMode" to "auto|ext|multiindirect|indirect|basevertex|drawelements|compute",
)
environmentSources.forEach { source ->
val text = source.readText()
name.findAll(text).forEach { names.add(it.groupValues[1]) }
query.findAll(text).forEach { types[it.groupValues[2]] = choices.getValue(it.groupValues[1]) }
}
types.putAll(mapOf(
"MOBILEGL_BACKEND_TYPE" to "DirectGLES|DirectVulkan",
"MOBILEGL_TRANSPORT" to "monolith|inproc|spawn",
"MOBILEGL_IPC_DATA" to "auto|shm|stream",
"MOBILEGL_IPC_SURFACE" to "offscreen|server",
"MOBILEGL_IPC_RECOVER" to choices.getValue("Flag"),
"MOBILEGL_FPS_LOG" to choices.getValue("Flag"),
"MOBILEGL_ES_CONTEXT_IDENTITY" to choices.getValue("Flag"),
))
names.remove("MOBILEGL_TEST_BACKEND_ENV_PRIORITY")
val asset = environmentAssets.get().file("test-environment.tsv").asFile
asset.parentFile.mkdirs()
asset.writeText(names.joinToString("\n", postfix = "\n") { "$it\t${types[it].orEmpty()}" })
}
}
tasks.named("preBuild").configure { dependsOn(generateTestEnvironment) }
android {
sourceSets.getByName("main").assets.srcDir(environmentAssets)
namespace = "top.mobilegl.plugin"
compileSdk = 34
ndkVersion = "27.3.13750724"
@@ -260,12 +303,6 @@ android.applicationVariants.configureEach {
}
}
androidComponents {
onVariants(selector().withFlavor("profile" to "plugin")) { variant ->
variant.packaging.jniLibs.excludes.add("**/libtrace_replay_runner.so")
}
}
dependencies {
implementation(project(":MobileGL"))
}
@@ -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