From 1e5d28909c4032505f05e7bab9bc746b5c934ea2 Mon Sep 17 00:00:00 2001 From: bitsandfoxes Date: Tue, 1 Dec 2026 15:00:36 +0100 Subject: [PATCH 01/10] feat(replay): Add hooks for a recorder of a Hybrid SDK and raw pixel frames Hybrid SDKs, such as Unity, capture the screen themselves. A recorder factory set on ReplayIntegration replaces the replay's own recorder, and onFrame takes frames as RGBA pixels, copied into a reused bitmap on the replay's thread. --- .../api/sentry-android-replay.api | 12 ++- .../android/replay/ReplayIntegration.kt | 96 ++++++++++++++++--- .../android/replay/ReplayRecorderFactory.kt | 30 ++++++ .../android/replay/ReplayIntegrationTest.kt | 73 ++++++++++++++ 4 files changed, 196 insertions(+), 15 deletions(-) create mode 100644 sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayRecorderFactory.kt diff --git a/sentry-android-replay/api/sentry-android-replay.api b/sentry-android-replay/api/sentry-android-replay.api index 1abe170ef99..7ab6324b3e2 100644 --- a/sentry-android-replay/api/sentry-android-replay.api +++ b/sentry-android-replay/api/sentry-android-replay.api @@ -53,7 +53,11 @@ public final class io/sentry/android/replay/ReplayCache : java/io/Closeable { public static synthetic fun createVideoOf$default (Lio/sentry/android/replay/ReplayCache;JJIIIIILjava/io/File;ILjava/lang/Object;)Lio/sentry/android/replay/GeneratedVideo; } -public final class io/sentry/android/replay/ReplayIntegration : io/sentry/IConnectionStatusProvider$IConnectionStatusObserver, io/sentry/Integration, io/sentry/ReplayController, io/sentry/android/replay/ScreenshotRecorderCallback, io/sentry/android/replay/WindowCallback, io/sentry/android/replay/gestures/TouchRecorderCallback, io/sentry/transport/RateLimiter$IRateLimitObserver, java/io/Closeable { +public abstract interface class io/sentry/android/replay/ReplayFrameReceiver { + public abstract fun onFrame ([BII)V +} + +public final class io/sentry/android/replay/ReplayIntegration : io/sentry/IConnectionStatusProvider$IConnectionStatusObserver, io/sentry/Integration, io/sentry/ReplayController, io/sentry/android/replay/ReplayFrameReceiver, io/sentry/android/replay/ScreenshotRecorderCallback, io/sentry/android/replay/WindowCallback, io/sentry/android/replay/gestures/TouchRecorderCallback, io/sentry/transport/RateLimiter$IRateLimitObserver, java/io/Closeable { public static final field $stable I public fun (Landroid/content/Context;Lio/sentry/transport/ICurrentDateProvider;)V public fun (Landroid/content/Context;Lio/sentry/transport/ICurrentDateProvider;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function1;)V @@ -73,6 +77,7 @@ public final class io/sentry/android/replay/ReplayIntegration : io/sentry/IConne public fun onAppSessionEnded ()V public final fun onConfigurationChanged (Lio/sentry/android/replay/ScreenshotRecorderConfig;)V public fun onConnectionStatusChanged (Lio/sentry/IConnectionStatusProvider$ConnectionStatus;)V + public fun onFrame ([BII)V public fun onRateLimitChanged (Lio/sentry/transport/RateLimiter;)V public fun onScreenshotRecorded (Landroid/graphics/Bitmap;)V public fun onScreenshotRecorded (Ljava/io/File;J)V @@ -86,11 +91,16 @@ public final class io/sentry/android/replay/ReplayIntegration : io/sentry/IConne public fun resume ()V public fun resumeTouchTracking ()V public fun setBreadcrumbConverter (Lio/sentry/ReplayBreadcrumbConverter;)V + public final fun setRecorderFactory (Lio/sentry/android/replay/ReplayRecorderFactory;)V public fun start ()V public fun startBuffering ()V public fun stop ()V } +public abstract interface class io/sentry/android/replay/ReplayRecorderFactory { + public abstract fun create (Lio/sentry/android/replay/ReplayFrameReceiver;)Lio/sentry/android/replay/Recorder; +} + public abstract interface class io/sentry/android/replay/ScreenshotRecorderCallback { public abstract fun onScreenshotRecorded (Landroid/graphics/Bitmap;)V public abstract fun onScreenshotRecorded (Ljava/io/File;J)V diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt index 6bdca6f748f..63f3b83a5bf 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt @@ -57,6 +57,7 @@ import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion import io.sentry.util.Random import java.io.Closeable import java.io.File +import java.nio.ByteBuffer import java.util.Date import java.util.LinkedList import java.util.concurrent.CopyOnWriteArraySet @@ -66,6 +67,7 @@ import java.util.concurrent.ThreadFactory import java.util.concurrent.TimeUnit.MILLISECONDS import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference +import org.jetbrains.annotations.ApiStatus public class ReplayIntegration( private val context: Context, @@ -76,6 +78,7 @@ public class ReplayIntegration( Integration, Closeable, ScreenshotRecorderCallback, + ReplayFrameReceiver, TouchRecorderCallback, ReplayController, IConnectionStatusObserver, @@ -118,6 +121,9 @@ public class ReplayIntegration( private lateinit var options: SentryOptions private var scopes: IScopes? = null private var recorder: Recorder? = null + @Volatile private var recorderFactory: ReplayRecorderFactory? = null + // Only the replay executor, where the capture strategies store frames, touches it. + private var pixelsFrame: Bitmap? = null private var gestureRecorder: GestureRecorder? = null private val random = ThreadLocal() internal val rootViewsSpy by lazy { RootViewsSpy.install() } @@ -150,6 +156,17 @@ public class ReplayIntegration( private var gestureRecorderProvider: (() -> GestureRecorder)? = null private val state = AtomicReference(ReplayState()) + /** + * Sets the factory of the [Recorder] that captures frames in place of the replay's own one, which + * draws the app's views. It takes effect when this integration registers, so it must be set + * before, e.g. in the options configuration callback of `SentryAndroid.init`. The recorder hands + * its frames to [onFrame]. + */ + @ApiStatus.Internal + public fun setRecorderFactory(factory: ReplayRecorderFactory?) { + recorderFactory = factory + } + override fun register(scopes: IScopes, options: SentryOptions) { this.options = options @@ -161,6 +178,7 @@ public class ReplayIntegration( this.scopes = scopes recorder = recorderProvider?.invoke() + ?: recorderFactory?.create(this) ?: WindowRecorder(options, this, this, mainLooperHandler, replayExecutor) gestureRecorder = gestureRecorderProvider?.invoke() ?: GestureRecorder(options, this) isEnabled.set(true) @@ -478,23 +496,73 @@ public class ReplayIntegration( var screen: String? = null scopes?.configureScope { screen = it.screen?.substringAfterLast('.') } state.get().captureStrategy?.onScreenshotRecorded(bitmap) { frameTimeStamp -> - val observer = options.sessionReplay.frameObserver - if (observer != null) { - val copy = bitmap.copy(bitmap.config!!, false) - if (copy != null) { - try { - val hint = Hint() - hint.set(TypeCheckHint.REPLAY_FRAME_BITMAP, copy) - observer.onMaskedFrameCaptured(hint, frameTimeStamp, screen) - } catch (e: Throwable) { - options.logger.log(ERROR, "Error in ReplayFrameObserver", e) - copy.recycle() - } + addBitmapFrame(bitmap, frameTimeStamp, screen) + } + enqueueOnMainThread { checkCanRecord() } + } + + /** + * Records a frame the recorder of [setRecorderFactory] captured. The calling thread only hands it + * over: the pixels are copied into a bitmap and stored on the replay's own thread. A frame that + * arrives while the replay is stopped or paused is dropped. + */ + override fun onFrame(pixels: ByteArray, width: Int, height: Int) { + val current = state.get() + if (current.lifecycleState != STARTED && current.lifecycleState != RESUMED) { + return + } + val captureStrategy = current.captureStrategy ?: return + if (width <= 0 || height <= 0 || pixels.size.toLong() != width.toLong() * height * 4) { + options.logger.log( + ERROR, + "Session replay dropped a frame of %d bytes, which doesn't hold %dx%d RGBA pixels", + pixels.size, + width, + height, + ) + return + } + + var screen: String? = null + scopes?.configureScope { screen = it.screen?.substringAfterLast('.') } + captureStrategy.onScreenshotRecorded { frameTimeStamp -> + addBitmapFrame(pixelsFrameOf(pixels, width, height), frameTimeStamp, screen) + } + enqueueOnMainThread { checkCanRecord() } + } + + private fun pixelsFrameOf(pixels: ByteArray, width: Int, height: Int): Bitmap { + val reused = pixelsFrame + val bitmap = + if (reused != null && reused.width == width && reused.height == height) { + reused + } else { + reused?.recycle() + Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).also { + it.setHasAlpha(false) + pixelsFrame = it + } + } + bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(pixels)) + return bitmap + } + + private fun ReplayCache.addBitmapFrame(bitmap: Bitmap, frameTimeStamp: Long, screen: String?) { + val observer = options.sessionReplay.frameObserver + if (observer != null) { + val copy = bitmap.copy(bitmap.config!!, false) + if (copy != null) { + try { + val hint = Hint() + hint.set(TypeCheckHint.REPLAY_FRAME_BITMAP, copy) + observer.onMaskedFrameCaptured(hint, frameTimeStamp, screen) + } catch (e: Throwable) { + options.logger.log(ERROR, "Error in ReplayFrameObserver", e) + copy.recycle() } } - addFrame(bitmap, frameTimeStamp, screen) } - enqueueOnMainThread { checkCanRecord() } + addFrame(bitmap, frameTimeStamp, screen) } override fun onScreenshotRecorded(screenshot: File, frameTimestamp: Long) { diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayRecorderFactory.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayRecorderFactory.kt new file mode 100644 index 00000000000..e5e9b303042 --- /dev/null +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayRecorderFactory.kt @@ -0,0 +1,30 @@ +package io.sentry.android.replay + +import org.jetbrains.annotations.ApiStatus + +/** + * Creates the [Recorder] that captures session replay frames in place of the replay's own one. + * Meant for Hybrid SDKs that capture frames themselves. + */ +@ApiStatus.Internal +public fun interface ReplayRecorderFactory { + /** + * @param frames takes the frames the returned recorder captures + * @return the recorder session replay starts, pauses, resumes and stops + */ + public fun create(frames: ReplayFrameReceiver): Recorder +} + +/** Takes session replay frames that a [Recorder] captured as raw pixels. */ +@ApiStatus.Internal +public interface ReplayFrameReceiver { + /** + * Takes one frame. The receiver owns [pixels] from then on: the caller must not change the array + * after the call. + * + * @param pixels [width] * [height] * 4 bytes, in RGBA order, top row first. Alpha is ignored. + * @param width the frame's width in pixels + * @param height the frame's height in pixels + */ + public fun onFrame(pixels: ByteArray, width: Int, height: Int) +} diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt index d66584f1085..3f94e0256cb 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt @@ -4,6 +4,7 @@ import android.content.Context import android.graphics.Bitmap import android.graphics.Bitmap.CompressFormat.JPEG import android.graphics.Bitmap.Config.ARGB_8888 +import android.graphics.Color import android.os.Looper import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 @@ -88,6 +89,7 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode @RunWith(AndroidJUnit4::class) @Config(sdk = [30], shadows = [ReplayShadowMediaCodec::class]) @@ -1976,6 +1978,77 @@ class ReplayIntegrationTest { assertTrue(replay.persistingExecutor.isShutdown) } + @Test + fun `registers the recorder of the recorder factory, which hands frames to the integration`() { + val recorder = mock() + var receiver: ReplayFrameReceiver? = null + val replay = fixture.getSut(context) + replay.setRecorderFactory { frames -> + receiver = frames + recorder + } + + replay.register(fixture.scopes, fixture.options) + replay.start() + + assertThat(receiver).isSameInstanceAs(replay) + verify(recorder).start() + } + + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) + fun `onFrame stores the pixels as a frame of their size`() { + val frames = mutableListOf() + whenever(fixture.replayCache.addFrame(any(), any(), anyOrNull())).doAnswer { + val bitmap = it.arguments[0] as Bitmap + frames += bitmap.copy(bitmap.config!!, false) + } + val captureStrategy = + mock { + doAnswer { + ((it.arguments[1] as ReplayCache.(frameTimestamp: Long) -> Unit)).invoke( + fixture.replayCache, + 1720693523997, + ) + } + .whenever(mock) + .onScreenshotRecorded(anyOrNull(), any()) + } + val replay = fixture.getSut(context, replayCaptureStrategyProvider = { captureStrategy }) + fixture.scopes.configureScope { it.screen = "MainActivity" } + replay.register(fixture.scopes, fixture.options) + replay.start() + + val red = byteArrayOf(-1, 0, 0, -1) + val blue = byteArrayOf(0, 0, -1, -1) + replay.onFrame(red + blue, 2, 1) + replay.onFrame(blue + red, 1, 2) + + verify(fixture.replayCache, times(2)) + .addFrame(any(), eq(1720693523997), eq("MainActivity")) + assertThat(frames.map { it.width to it.height }).containsExactly(2 to 1, 1 to 2).inOrder() + assertThat(frames[0].getPixel(0, 0)).isEqualTo(Color.RED) + assertThat(frames[0].getPixel(1, 0)).isEqualTo(Color.BLUE) + assertThat(frames[1].getPixel(0, 0)).isEqualTo(Color.BLUE) + assertThat(frames[1].getPixel(0, 1)).isEqualTo(Color.RED) + } + + @Test + fun `onFrame drops frames while stopped or paused, or of the wrong size`() { + val captureStrategy = mock() + val replay = fixture.getSut(context, replayCaptureStrategyProvider = { captureStrategy }) + replay.register(fixture.scopes, fixture.options) + + replay.onFrame(ByteArray(8), 2, 1) + replay.start() + replay.onFrame(ByteArray(4), 2, 1) + replay.onFrame(ByteArray(0), 0, 0) + replay.pause() + replay.onFrame(ByteArray(8), 2, 1) + + verify(captureStrategy, never()).onScreenshotRecorded(anyOrNull(), any()) + } + private fun getSessionCaptureStrategy(options: SentryOptions): SessionCaptureStrategy = SessionCaptureStrategy( options, From 08cc7660fc6d3b01e9e5d1f2bddf9475cf0cb9b0 Mon Sep 17 00:00:00 2001 From: bitsandfoxes Date: Tue, 1 Dec 2026 15:11:40 +0100 Subject: [PATCH 02/10] test(replay): Prove the Hybrid SDK recorder hooks with Unity on a device From 157a4f467e3678e462bd2d627cc9adc56b6dd869 Mon Sep 17 00:00:00 2001 From: bitsandfoxes Date: Tue, 1 Dec 2026 15:13:28 +0100 Subject: [PATCH 03/10] docs(replay): Say a Hybrid SDK recorder must report its frame size --- .../main/java/io/sentry/android/replay/ReplayIntegration.kt | 4 +++- .../java/io/sentry/android/replay/ReplayRecorderFactory.kt | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt index 63f3b83a5bf..7106dea0b70 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt @@ -160,7 +160,9 @@ public class ReplayIntegration( * Sets the factory of the [Recorder] that captures frames in place of the replay's own one, which * draws the app's views. It takes effect when this integration registers, so it must be set * before, e.g. in the options configuration callback of `SentryAndroid.init`. The recorder hands - * its frames to [onFrame]. + * its frames to [onFrame]. Nothing reports the frame size for it, so once the replay is recording + * the Hybrid SDK must call [onConfigurationChanged] with its frame size, and every frame must + * match the config's `recordingWidth` x `recordingHeight`: until then no segment is sent. */ @ApiStatus.Internal public fun setRecorderFactory(factory: ReplayRecorderFactory?) { diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayRecorderFactory.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayRecorderFactory.kt index e5e9b303042..6469f8ed7fc 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayRecorderFactory.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayRecorderFactory.kt @@ -20,7 +20,9 @@ public fun interface ReplayRecorderFactory { public interface ReplayFrameReceiver { /** * Takes one frame. The receiver owns [pixels] from then on: the caller must not change the array - * after the call. + * after the call. The frame must be [ScreenshotRecorderConfig.recordingWidth] x + * [ScreenshotRecorderConfig.recordingHeight] of the config last passed to + * [ReplayIntegration.onConfigurationChanged], or it is cropped or padded in the video. * * @param pixels [width] * [height] * 4 bytes, in RGBA order, top row first. Alpha is ignored. * @param width the frame's width in pixels From c5b95c3c55e222fc35290685c902255604a96c91 Mon Sep 17 00:00:00 2001 From: bitsandfoxes Date: Tue, 1 Dec 2026 15:41:21 +0100 Subject: [PATCH 04/10] changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d64209bed76..a7dbaa50337 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ ### Internal - Add a `WebView.loadUrl` adapter for automatic WebView trace propagation in the Sentry Android Gradle Plugin ([#6592](https://github.com/getsentry/sentry-java/pull/6592)) +- Session Replay: Add hooks for hybrid SDKs, such as Unity, to record replays with their own recorder and hand in frames as raw pixels ([#6829](https://github.com/getsentry/sentry-java/pull/6829)) ### Dependencies From 743dfa31bfcf94ff8c0278b5a1abac7b426d685a Mon Sep 17 00:00:00 2001 From: bitsandfoxes Date: Tue, 1 Dec 2026 15:51:03 +0100 Subject: [PATCH 05/10] ref(replay): Name the RGBA bytes per pixel and update the detekt baseline --- sentry-android-replay/detekt-baseline.xml | 3 ++- .../java/io/sentry/android/replay/ReplayIntegration.kt | 8 +++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/sentry-android-replay/detekt-baseline.xml b/sentry-android-replay/detekt-baseline.xml index 19845da6ac5..4859c51bd6d 100644 --- a/sentry-android-replay/detekt-baseline.xml +++ b/sentry-android-replay/detekt-baseline.xml @@ -44,6 +44,7 @@ FunctionParameterNaming:PixelCopyStrategyTest.kt$DeferredWindowPixelCopyShadow.Companion$_source: Window LargeClass:CanvasStrategy.kt$TextIgnoringDelegateCanvas : Canvas LargeClass:ReplayCacheTest.kt$ReplayCacheTest + LargeClass:ReplayIntegration.kt$ReplayIntegration : IntegrationCloseableScreenshotRecorderCallbackReplayFrameReceiverTouchRecorderCallbackReplayControllerIConnectionStatusObserverIRateLimitObserverWindowCallback LargeClass:ReplayIntegrationTest.kt$ReplayIntegrationTest LongMethod:CaptureStrategy.kt$CaptureStrategy.Companion$@Suppress("NewApi") private fun buildReplay( options: SentryOptions, video: File, currentReplayId: SentryId, segmentTimestamp: Date, segmentId: Int, height: Int, width: Int, frameCount: Int, frameRate: Int, videoDuration: Long, replayType: ReplayType, screenAtStart: String?, breadcrumbs: List<Breadcrumb>, events: Deque<RRWebEvent>, traceIds: List<String>, segmentNames: List<String>, ): ReplaySegment LongMethod:ComposeViewHierarchyNode.kt$ComposeViewHierarchyNode$private fun fromComposeNode( node: LayoutNode, parent: ViewHierarchyNode?, distance: Int, isComposeRoot: Boolean, options: SentryMaskingOptions, logger: ILogger, ): ViewHierarchyNode? @@ -154,7 +155,7 @@ TooManyFunctions:CanvasStrategy.kt$TextIgnoringDelegateCanvas : Canvas TooManyFunctions:CaptureStrategy.kt$CaptureStrategy TooManyFunctions:PixelCopyStrategy.kt$PixelCopyStrategy : ScreenshotStrategy - TooManyFunctions:ReplayIntegration.kt$ReplayIntegration : IntegrationCloseableScreenshotRecorderCallbackTouchRecorderCallbackReplayControllerIConnectionStatusObserverIRateLimitObserverWindowCallback + TooManyFunctions:ReplayIntegration.kt$ReplayIntegration : IntegrationCloseableScreenshotRecorderCallbackReplayFrameReceiverTouchRecorderCallbackReplayControllerIConnectionStatusObserverIRateLimitObserverWindowCallback TooManyFunctions:WindowRecorder.kt$WindowRecorder : RecorderOnRootViewsChangedListenerExecutorProvider UnusedPrivateProperty:DebugOverlayDrawable.kt$DebugOverlayDrawable$private val padding = 6f UseCheckOrError:ReplayShadowMediaCodec.kt$ReplayShadowMediaCodec$throw IllegalStateException("Simulated codec start failure") diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt index 7106dea0b70..9027e071d5c 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt @@ -94,6 +94,8 @@ public class ReplayIntegration( // read after the replay stopped, so the startup cleanup of previous replays must keep them. // Shared across instances, because a second SDK init registers a new ReplayIntegration. val replayIdsOfThisProcess = CopyOnWriteArraySet() + + const val RGBA_BYTES_PER_PIXEL = 4 } // needed for the Java's call site @@ -514,7 +516,11 @@ public class ReplayIntegration( return } val captureStrategy = current.captureStrategy ?: return - if (width <= 0 || height <= 0 || pixels.size.toLong() != width.toLong() * height * 4) { + if ( + width <= 0 || + height <= 0 || + pixels.size.toLong() != width.toLong() * height * RGBA_BYTES_PER_PIXEL + ) { options.logger.log( ERROR, "Session replay dropped a frame of %d bytes, which doesn't hold %dx%d RGBA pixels", From 6fbffc302e36be636f40091b99f992419b526f93 Mon Sep 17 00:00:00 2001 From: bitsandfoxes Date: Tue, 1 Dec 2026 15:51:39 +0100 Subject: [PATCH 06/10] ref(replay): Keep the RGBA bytes-per-pixel constant private --- .../src/main/java/io/sentry/android/replay/ReplayIntegration.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt index 9027e071d5c..7108c5f8953 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt @@ -95,7 +95,7 @@ public class ReplayIntegration( // Shared across instances, because a second SDK init registers a new ReplayIntegration. val replayIdsOfThisProcess = CopyOnWriteArraySet() - const val RGBA_BYTES_PER_PIXEL = 4 + private const val RGBA_BYTES_PER_PIXEL = 4 } // needed for the Java's call site From 90303e16483102d8cd68d7ff30e3080eda0b83a5 Mon Sep 17 00:00:00 2001 From: bitsandfoxes Date: Tue, 1 Dec 2026 15:52:39 +0100 Subject: [PATCH 07/10] fix(replay): Drop the recycled frame bitmap before allocating a new one --- .../src/main/java/io/sentry/android/replay/ReplayIntegration.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt index 7108c5f8953..778c112f43e 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt @@ -546,6 +546,7 @@ public class ReplayIntegration( reused } else { reused?.recycle() + pixelsFrame = null Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).also { it.setHasAlpha(false) pixelsFrame = it From 589aea69c58c9ab6aace546109150adee4e99c66 Mon Sep 17 00:00:00 2001 From: bitsandfoxes Date: Tue, 1 Dec 2026 16:01:27 +0100 Subject: [PATCH 08/10] test(replay): Make the onFrame pixel check independent of the host's byte order --- .../android/replay/ReplayIntegrationTest.kt | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt index 3f94e0256cb..419b0651273 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt @@ -2019,18 +2019,19 @@ class ReplayIntegrationTest { replay.register(fixture.scopes, fixture.options) replay.start() - val red = byteArrayOf(-1, 0, 0, -1) - val blue = byteArrayOf(0, 0, -1, -1) - replay.onFrame(red + blue, 2, 1) - replay.onFrame(blue + red, 1, 2) + // Red and blue equal in both colours: Robolectric's native bitmaps use the host's byte order. + val green = byteArrayOf(0, -1, 0, -1) + val white = byteArrayOf(-1, -1, -1, -1) + replay.onFrame(green + white, 2, 1) + replay.onFrame(white + green, 1, 2) verify(fixture.replayCache, times(2)) .addFrame(any(), eq(1720693523997), eq("MainActivity")) assertThat(frames.map { it.width to it.height }).containsExactly(2 to 1, 1 to 2).inOrder() - assertThat(frames[0].getPixel(0, 0)).isEqualTo(Color.RED) - assertThat(frames[0].getPixel(1, 0)).isEqualTo(Color.BLUE) - assertThat(frames[1].getPixel(0, 0)).isEqualTo(Color.BLUE) - assertThat(frames[1].getPixel(0, 1)).isEqualTo(Color.RED) + assertThat(frames[0].getPixel(0, 0)).isEqualTo(Color.GREEN) + assertThat(frames[0].getPixel(1, 0)).isEqualTo(Color.WHITE) + assertThat(frames[1].getPixel(0, 0)).isEqualTo(Color.WHITE) + assertThat(frames[1].getPixel(0, 1)).isEqualTo(Color.GREEN) } @Test From 3b10c0c177e609e00916c980aefacd73b0582534 Mon Sep 17 00:00:00 2001 From: bitsandfoxes Date: Tue, 1 Dec 2026 17:42:53 +0100 Subject: [PATCH 09/10] ref(replay): Pass the replay cache to addBitmapFrame and name sentry-unity in the changelog --- CHANGELOG.md | 2 +- .../io/sentry/android/replay/ReplayIntegration.kt | 13 +++++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a7dbaa50337..dc1a8ce4d74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,7 @@ ### Internal - Add a `WebView.loadUrl` adapter for automatic WebView trace propagation in the Sentry Android Gradle Plugin ([#6592](https://github.com/getsentry/sentry-java/pull/6592)) -- Session Replay: Add hooks for hybrid SDKs, such as Unity, to record replays with their own recorder and hand in frames as raw pixels ([#6829](https://github.com/getsentry/sentry-java/pull/6829)) +- Session Replay: Add hooks for hybrid SDKs, such as `sentry-unity`, to record replays with their own recorder and hand in frames as raw pixels ([#6829](https://github.com/getsentry/sentry-java/pull/6829)) ### Dependencies diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt index 778c112f43e..65fb111764e 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt @@ -500,7 +500,7 @@ public class ReplayIntegration( var screen: String? = null scopes?.configureScope { screen = it.screen?.substringAfterLast('.') } state.get().captureStrategy?.onScreenshotRecorded(bitmap) { frameTimeStamp -> - addBitmapFrame(bitmap, frameTimeStamp, screen) + addBitmapFrame(this, bitmap, frameTimeStamp, screen) } enqueueOnMainThread { checkCanRecord() } } @@ -534,7 +534,7 @@ public class ReplayIntegration( var screen: String? = null scopes?.configureScope { screen = it.screen?.substringAfterLast('.') } captureStrategy.onScreenshotRecorded { frameTimeStamp -> - addBitmapFrame(pixelsFrameOf(pixels, width, height), frameTimeStamp, screen) + addBitmapFrame(this, pixelsFrameOf(pixels, width, height), frameTimeStamp, screen) } enqueueOnMainThread { checkCanRecord() } } @@ -556,7 +556,12 @@ public class ReplayIntegration( return bitmap } - private fun ReplayCache.addBitmapFrame(bitmap: Bitmap, frameTimeStamp: Long, screen: String?) { + private fun addBitmapFrame( + cache: ReplayCache, + bitmap: Bitmap, + frameTimeStamp: Long, + screen: String?, + ) { val observer = options.sessionReplay.frameObserver if (observer != null) { val copy = bitmap.copy(bitmap.config!!, false) @@ -571,7 +576,7 @@ public class ReplayIntegration( } } } - addFrame(bitmap, frameTimeStamp, screen) + cache.addFrame(bitmap, frameTimeStamp, screen) } override fun onScreenshotRecorded(screenshot: File, frameTimestamp: Long) { From 9e8b2d4928008fbd7045f1ceab4997dad1a9b21c Mon Sep 17 00:00:00 2001 From: bitsandfoxes Date: Tue, 1 Dec 2026 17:54:30 +0100 Subject: [PATCH 10/10] ref(replay): Name the reused frame bitmap helper for what it does --- .../android/replay/ReplayIntegration.kt | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt index 65fb111764e..fb0547fa230 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt @@ -125,7 +125,7 @@ public class ReplayIntegration( private var recorder: Recorder? = null @Volatile private var recorderFactory: ReplayRecorderFactory? = null // Only the replay executor, where the capture strategies store frames, touches it. - private var pixelsFrame: Bitmap? = null + private var frameBitmap: Bitmap? = null private var gestureRecorder: GestureRecorder? = null private val random = ThreadLocal() internal val rootViewsSpy by lazy { RootViewsSpy.install() } @@ -534,28 +534,30 @@ public class ReplayIntegration( var screen: String? = null scopes?.configureScope { screen = it.screen?.substringAfterLast('.') } captureStrategy.onScreenshotRecorded { frameTimeStamp -> - addBitmapFrame(this, pixelsFrameOf(pixels, width, height), frameTimeStamp, screen) + addBitmapFrame(this, fillFrameBitmap(pixels, width, height), frameTimeStamp, screen) } enqueueOnMainThread { checkCanRecord() } } - private fun pixelsFrameOf(pixels: ByteArray, width: Int, height: Int): Bitmap { - val reused = pixelsFrame + /** Copies [pixels] into [frameBitmap], which is reused while the frame size stays the same. */ + private fun fillFrameBitmap(pixels: ByteArray, width: Int, height: Int): Bitmap { val bitmap = - if (reused != null && reused.width == width && reused.height == height) { - reused - } else { - reused?.recycle() - pixelsFrame = null - Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).also { - it.setHasAlpha(false) - pixelsFrame = it - } - } + frameBitmap?.takeIf { it.width == width && it.height == height } + ?: newFrameBitmap(width, height) bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(pixels)) return bitmap } + private fun newFrameBitmap(width: Int, height: Int): Bitmap { + frameBitmap?.recycle() + // A failed allocation must not leave the recycled bitmap for a later frame of the old size. + frameBitmap = null + return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).also { + it.setHasAlpha(false) + frameBitmap = it + } + } + private fun addBitmapFrame( cache: ReplayCache, bitmap: Bitmap,