diff --git a/CHANGELOG.md b/CHANGELOG.md
index 35a786754..8678c2e19 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,18 @@
# Changelog
+## Unreleased
+
+### Features
+
+- Experimental session replay on Android ([#2948](https://github.com/getsentry/sentry-unity/pull/2948)):
+ - Set `options.Experimental.SessionReplay.SessionSampleRate` or `OnErrorSampleRate` in code,
+ in the options used both at build time and at runtime.
+ - The Android SDK records the game, and errors captured in C# send the replay of the moments before them,
+ like native errors do.
+ - Session replay requires runtime initialization of the Android SDK and adds the Kotlin standard library to the build.
+ - By default, the Android SDK captures the frames; with `Capture = SessionReplayCapture.Unity`,
+ Unity captures them instead.
+
## 4.13.0
### Behavioral Changes
diff --git a/build/native-sdks.targets b/build/native-sdks.targets
index f15748bd4..bf9aea0f5 100644
--- a/build/native-sdks.targets
+++ b/build/native-sdks.targets
@@ -294,6 +294,7 @@
+
@@ -302,16 +303,18 @@
-
+
+
+
diff --git a/docs/agent-guides/platform-android.md b/docs/agent-guides/platform-android.md
index 02c4dda75..54fb565ed 100644
--- a/docs/agent-guides/platform-android.md
+++ b/docs/agent-guides/platform-android.md
@@ -20,6 +20,60 @@
The Java layer disables duplicate screenshots, auto-session tracking, activity lifecycle breadcrumbs, and user-interaction breadcrumbs/tracing because Unity/.NET owns them.
+## Session Replay (Experimental)
+
+- `options.Experimental.SessionReplay` is set from code, with no editor UI.
+ Replay is enabled when `SessionSampleRate` or `OnErrorSampleRate` is above 0.
+- Packaging:
+ - `sentry-android-replay-release.aar` ships in `Sentry~` next to the other artifacts.
+ - `GradleSetup` adds it to `unityLibrary/build.gradle` only when replay is enabled in the build-time options,
+ together with `org.jetbrains.kotlin:kotlin-stdlib` from Maven, at the version sentry-android-replay builds with.
+ - Without replay, the Sentry dependency block is unchanged.
+ - Adding and clearing recognize both variants of the block,
+ so a persisted Gradle project follows replay and native support being toggled.
+- Replay is runtime-init only:
+ - `SentryJava.Init` configures the replay options: sample rates, quality,
+ and SurfaceView capture when sentry-java captures the frames, since Unity renders into a SurfaceView.
+ - Build-time and external initialization log that replay is ignored.
+ - A missing replay library logs an error asking to enable replay in the build-time options.
+- Unity capture (`Capture = SessionReplayCapture.Unity`):
+ - Without `SystemInfo.supportsAsyncGPUReadback`, `SentryJava.Init` logs a warning and sentry-java captures instead.
+ - `UnityReplayRecorder` replaces the `ReplayIntegration` sentry-java added with one built through JNI
+ around a custom `Recorder`: a Unity `AndroidJavaProxy`, returned by a `kotlin.jvm.functions.Function0` proxy.
+ - sentry-java calls the recorder on Android's UI thread, which only updates flags and the frame config.
+ - sentry-java never sends a custom recorder a frame config. After each start or reset,
+ and when Unity's screen size changes, Unity's main thread asks the UI thread to call `onWindowSizeChanged`
+ with the activity window's size, and sentry-java computes the config from it.
+ Before the window is laid out, Unity's screen size stands in once, and a later frame asks again.
+ - It gets the window's size, not `Screen.width/height`, which can be a lower render resolution:
+ sentry-java scales recorded touches, which are in window pixels, by that config.
+ - At the config's frame rate, Unity's main thread captures the screen at end of frame,
+ blits it top-down into an RGBA render texture at the recording size (`SentryScreenshot.BlitScreen`)
+ and reads it back with `AsyncGPUReadback`.
+ - A worker thread attached to the JVM copies each frame into a new `ARGB_8888` bitmap
+ and calls `onScreenshotRecorded`.
+ - A started recorder captures until it's paused: sentry-java only resumes a paused one.
+- `proguard-sentry-unity.pro` keeps the replay classes Unity reaches through JNI and proxies,
+ and the classes in the JNI signatures it looks up (`ICurrentDateProvider`, `Integration`, `Function0`, `Function1`):
+ keeping a method doesn't keep the classes in its signature, so minified builds would rename them.
+- Replays for C# errors:
+ - sentry-java samples and starts the replay itself.
+ - `AndroidReplaySession` is the .NET SDK's replay session: the replay id of the dynamic sampling context
+ comes from the Java scope.
+ - The .NET client calls `captureReplay` for each error event
+ and puts the returned replay id on that event's dynamic sampling context.
+ Other events get the Java scope's current replay id.
+- Background and foreground:
+ - Unity builds don't start androidx's process lifecycle (the `lifecycle-process` startup provider isn't in the
+ manifest), so the Java SDK doesn't see the app go to the background.
+ When it isn't running, Unity's pause and resume drive the replay instead.
+ - A pause is the replay's manual pause. sentry-java resumes a replay paused for the background
+ when the device reconnects, which happens in the background too, but not a manually paused one.
+ - Resuming moves the replay's timeline to the return, so no segment covers the time away.
+ - After a background longer than `AutoSessionTrackingInterval`, the replay is resumed and then ended right away
+ (`onAppForegrounded(true)`), so it ends at the pause without a segment for the time away, and a new one starts.
+ - Unity capture drops frames read back or handed over after the pause, so none lands after the pause segment.
+
## Constraints
- Android native ANR and C# ANR monitor different threads; both can report one full hang.
diff --git a/package-dev/Plugins/Android/proguard-sentry-unity.pro b/package-dev/Plugins/Android/proguard-sentry-unity.pro
index 38aa01486..773aa803e 100644
--- a/package-dev/Plugins/Android/proguard-sentry-unity.pro
+++ b/package-dev/Plugins/Android/proguard-sentry-unity.pro
@@ -20,4 +20,22 @@
-keep class io.sentry.protocol.** { *; }
-keep class io.sentry.android.core.internal.util.AndroidConnectionStatusProvider { *; }
-keep class io.sentry.android.core.internal.util.NetworkConnection { *; }
+# Experimental session replay: options, the replay controller and the recorder Unity can provide.
+-keep class io.sentry.SentryReplayOptions { *; }
+-keep class io.sentry.SentryReplayOptions$SentryReplayQuality { *; }
+-keep interface io.sentry.ReplayController { *; }
+-keep class io.sentry.transport.CurrentDateProvider { *; }
+-keep class io.sentry.android.replay.ReplayIntegration { *; }
+-keep interface io.sentry.android.replay.Recorder { *; }
+-keep class io.sentry.android.replay.ScreenshotRecorderConfig { *; }
+-keep interface kotlin.jvm.functions.Function0 { *; }
+# The classes in the JNI signatures of the ReplayIntegration constructor and SentryOptions.addIntegration.
+-keep interface io.sentry.transport.ICurrentDateProvider { *; }
+-keep interface io.sentry.Integration { *; }
+-keep interface kotlin.jvm.functions.Function1 { *; }
+# Unity checks whether androidx's process lifecycle runs, to pause the replay itself when it doesn't.
+-keep class androidx.lifecycle.ProcessLifecycleOwner { *; }
+-keep class androidx.lifecycle.Lifecycle { *; }
+-keep class androidx.lifecycle.Lifecycle$State { *; }
+-dontwarn androidx.lifecycle.**
-dontwarn io.sentry.**
diff --git a/samples/unity-of-bugs-local/ProjectSettings/ProjectSettings.asset b/samples/unity-of-bugs-local/ProjectSettings/ProjectSettings.asset
index 51541be21..c6bfdd556 100644
--- a/samples/unity-of-bugs-local/ProjectSettings/ProjectSettings.asset
+++ b/samples/unity-of-bugs-local/ProjectSettings/ProjectSettings.asset
@@ -147,7 +147,7 @@ PlayerSettings:
vrSettings:
enable360StereoCapture: 0
isWsaHolographicRemotingEnabled: 0
- enableFrameTimingStats: 0
+ enableFrameTimingStats: 1
enableOpenGLProfilerGPURecorders: 1
useHDRDisplay: 0
D3DHDRBitDepth: 0
diff --git a/samples/unity-of-bugs/Assets/Scripts/ReplayBenchmark.cs b/samples/unity-of-bugs/Assets/Scripts/ReplayBenchmark.cs
new file mode 100644
index 000000000..42c8f4de8
--- /dev/null
+++ b/samples/unity-of-bugs/Assets/Scripts/ReplayBenchmark.cs
@@ -0,0 +1,151 @@
+#if UNITY_ANDROID && !UNITY_EDITOR
+using System.Collections.Generic;
+using UnityEngine;
+using UnityEngine.UI;
+
+// Spins a cube above the sample's UI, so session replays show motion, and logs frame timings to logcat under the
+// 'ReplayBenchmark' tag, to compare session replay's capture modes (see SentryOptionConfiguration).
+// Android players only. The GPU and per-thread timings need 'Frame Timing Stats' in the player settings.
+public class ReplayBenchmark : MonoBehaviour
+{
+ private const string LogTag = "ReplayBenchmark";
+ private const float WarmUpSeconds = 5f;
+ private const float ReportSeconds = 10f;
+ // A layer of its own, so the cube's camera and light leave the sample's scenes alone.
+ private const int CubeLayer = 31;
+
+ private readonly List _frameTimes = new();
+ private readonly FrameTiming[] _timings = new FrameTiming[1];
+ private double _cpuMainMs;
+ private double _cpuRenderMs;
+ private double _gpuMs;
+ private int _timingCount;
+ private float _collectFrom;
+ private float _nextReport;
+ private Transform _cube;
+ private string _mode;
+ private AndroidJavaClass _log;
+
+ [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
+ private static void Spawn()
+ {
+ var benchmark = new GameObject("ReplayBenchmark");
+ DontDestroyOnLoad(benchmark);
+ benchmark.AddComponent();
+ }
+
+ private void Start()
+ {
+ Application.targetFrameRate = 60;
+ _mode = $"replay={SentryOptionConfiguration.GetLaunchExtra("sentry_replay") ?? "error"} " +
+ $"capture={SentryOptionConfiguration.GetLaunchExtra("sentry_replay_capture") ?? "java"}";
+ _log = new AndroidJavaClass("android.util.Log");
+ _collectFrom = Time.realtimeSinceStartup + WarmUpSeconds;
+ _nextReport = _collectFrom + ReportSeconds;
+
+ var texture = new RenderTexture(256, 256, 16);
+
+ var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
+ cube.layer = CubeLayer;
+ cube.transform.SetParent(transform);
+ cube.transform.position = new Vector3(0, -1000, 0);
+ // A shader that builds always include. The primitive's default material doesn't make it into the player.
+ var shader = Shader.Find("Legacy Shaders/Diffuse");
+ var cubeRenderer = cube.GetComponent();
+ if (shader != null)
+ {
+ cubeRenderer.material = new Material(shader);
+ }
+ cubeRenderer.material.color = new Color(1f, 0.45f, 0.1f);
+ _cube = cube.transform;
+
+ var cubeCamera = new GameObject("ReplayBenchmarkCamera").AddComponent();
+ cubeCamera.transform.SetParent(transform);
+ cubeCamera.transform.position = _cube.position + new Vector3(0, 0, -2.5f);
+ cubeCamera.cullingMask = 1 << CubeLayer;
+ cubeCamera.clearFlags = CameraClearFlags.SolidColor;
+ cubeCamera.backgroundColor = new Color(0.1f, 0.5f, 0.9f);
+ cubeCamera.targetTexture = texture;
+
+ var cubeLight = new GameObject("ReplayBenchmarkLight").AddComponent();
+ cubeLight.transform.SetParent(transform);
+ cubeLight.type = LightType.Directional;
+ cubeLight.cullingMask = 1 << CubeLayer;
+ cubeLight.transform.rotation = Quaternion.Euler(40, -30, 0);
+
+ // Above the sample's UI, in the top right corner.
+ var canvas = new GameObject("ReplayBenchmarkCanvas").AddComponent